HTML and CSS Reference
In-Depth Information
Rebecca wants you to add onclick event handlers to each of these buttons. Because
each of the three buttons belongs to the object class puzzles , you can add the same
event handler by looping through the puzzleButtons object collection as follows:
var puzzleButtons = document.getElementsByClassName(“puzzles”);
for (var i = 0; i < puzzleButtons.length; i++) {
puzzleButtons[i].onclick = swapPuzzle;
}
The click event for each button is associated with the same swapPuzzle() function to
switch the puzzle displayed on the Web page. The advantage of this approach is that
Rebecca can add as many puzzles and as many puzzle buttons to her Web page as she
wishes; as long as each of those buttons belongs to the puzzles class, they all will be
associated with the same onclick event handler. You'll add this code to the init() func-
tion now so that the event handlers are automatically assigned when the page is initially
loaded by a browser.
To apply an onclick event handler to each puzzle button:
1. Return to the hanjie.js file in your text editor and add the following code to the
init() function, as displayed in Figure 13-10:
/* Add event handlers for the puzzle buttons */
var puzzleButtons = document.getElementsByClassName(“puzzles”);
for (var i = 0; i < puzzleButtons.length; i++) {
puzzleButtons[i].onclick = swapPuzzle;
}
Figure 13-10
adding onclick event handlers to the puzzle buttons
object collection of
elements with t he
class name "puzzles"
run the swapPuzzle()
function when the
buttons are clicked
2. Save your changes to the file.
Because each button calls the same swapPuzzle() function when clicked, how does
the function know which button called it? You can determine this information using the
this keyword.
Search WWH ::




Custom Search