254
Chapter 4.5
Add CD rankingsCreate JS le Add CD to Top 5
Start over
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>.
Adding event handlers
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.
function addOnClickHandlers() {
var cdsDiv = document.getElementById(“cds”);
var cdImages = cdsDiv.getElementsByTagName(“img”);
for (var i=0; i<cdImages.length; i++) {
cdImages[i].onclick = addToTop5;
}
}
All the CD covers we want to add
handlers to are nested in the “cds” <div>.
This will return an array of
all the elements named “img”
within the “cds” div.
Add this function
to top5.js.
“onclick” is the JavaScript
event that matches up with the
HTML onClick event handler...
...and addToTop5 is the function
to run on that event.
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 ...