Hands On: Completing Event Handling
Explore how to complete event handling in the DOM by coding a toggle function to collapse and expand sections with JavaScript. Understand navigating DOM nodes, creating and dispatching click events to enhance interactive web pages.
The previous exercise showed that you can easily change an element in the DOM. However, instead of setting the background color of headings to red, the <div> section adjacent with the <h2> should be hidden or shown again.
In the upcoming exercise, you will learn how to do it with the operations of the DOM.
EXERCISE: Completing event handling
To change the event handler method, follow these steps:
Step 1:
Switch back to the code editor below, and open hideandseek.js.
var titles = document.getElementsByTagName('h2');
for (var i = 0; i < titles.length; i++) {
var title = titles[i];
title.innerHTML = '<span class="mono">- </span>'
+ title.innerHTML;
title.addEventListener('click', onClick, true);
}
function onClick(evt) {
var headerClicked = evt.currentTarget;
headerClicked.setAttribute("style",
"background-color: red;");
}
Step 2:
Remove the body of the onClick() function, and change it to this:
Step 3:
Take a look at the page in the browser. When you click any of the headings, the related details are now collapsed, as shown in the image below:
Step 4:
When the page appears, it would be ...