Skip to Content
Head Rush Ajax
book

Head Rush Ajax

by Brett McLaughlin
March 2006
Beginner to intermediate
448 pages
13h 33m
English
O'Reilly Media, Inc.
Content preview from Head Rush Ajax
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

What Employees Want Most in Uncertain Times

What Employees Want Most in Uncertain Times

Kristine W. Powers, Jessica B.B. Diaz
What Successful Project Managers Do

What Successful Project Managers Do

W. Scott Cameron, Jeffrey S. Russell, Edward J. Hoffman, Alexander Laufer
How to Become a Game-Changing Leader

How to Become a Game-Changing Leader

Douglas A. Ready, Alan Mulally

Publisher Resources

ISBN: 0596102259Errata PageSupplemental Content