HTML5, CSS3, and JavaScript Fourth Edition

(Ben Green) #1

CHAPTER 36. CH32 UNTANGLING HTML AND SCRIPTING 294


36.1 Add Event Listener


The secret is to include some JavaScript that runs after your webpage has
loaded. It can wander through the DOM and add event listeners where you
want them.


Here is an example.



In this example, we use a JavaScript function, getElementsByClassName,
to search through the document tree for elements that belong to the class
abc. The variableelementsis used to hold a list of those elements.


Next, we walk down the list and perform theaddEventListenerprocedure
to each such element. Specifically we add an event listener for thekeypress
event.


This is essentially the same as if we had written:



But instead, we can write this in the HTML:



By doing this, we have removed almost all of the JavaScript from the HTML,
and isolated it to only a few places.


36.2 ezCalc


Here is a complete example.


<!DOCTYPE html>


ezCalc