Section 4a.6. Adding event handlers


4a.6. Adding event handlers

You've already used onClick and onChange in your HTML to assign a JavaScript function to an event. You can do the same thing with JavaScript code, and get a little practice working with the DOM, too. Let's create a new function, called addOnClickHandlers();, that will add event handlers to all the <img> elements in the "cds" <div> .

This wasn't on our original checklist back on page 247, but it's still part of setting up the CDs to be added to the Top 5 listings.

     Add this function to top5.js.     function addOnClickHandlers() {      var cdsDiv = document.getElementByIdAll the CD covers we want to add      handlers to are nested in the "cds" <div>.("cds");      var cdImages = cdsDiv.getElementsByTagName("img");This will return an array of      all the elements named "img" within the "cds" div.      for (var i=0; i<cdImages.length; i++) { We can just loop through      all the <img> elements, and add an event handler to each.       cdImages[i].onclick"onclick" is the JavaScript event that matches       up with the HTML onClick event handler... = addToTop5;...and       addToTop5 is the function to run on that event.      }     } 

Q:

Q: getElementsByTagName? What's that all about?

A:

The JavaScript document object, as well as all element nodes, has a method that you can run called getElementsByTagName(). That method returns all the nested elements that have the name you supplied. In this case, we want all the <img> elements in the "cds" <div>, so we call getElementsByTagName("img"). Remember, this method only returns matching elements nested within the node you run the method on... in this case, that's the cdsDiv node.

Q:

What's the difference between using the onclick property in JavaScript, and the onClick attribute in an HTML page?

A:

There's really no difference at all. However, as we discussed a few pages back, writing a method to take care of setting up event handlers is a little more flexible... and you can call this method multiple times, which will come in handy in just a bit.

Remember, the browser reads the markup in your HTML file, and then doesn't use that text file anymore. It converts the markup into a DOM tree, so it's reallly the DOM that you're working with here.




Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net