4a.6. Adding event handlersYou'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. } }
|