...

/

Hands On: Completing Event Handling

Hands On: Completing Event Handling

Let's complete event handling in this lesson.

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:

Press + to interact
function onClick(evt) {
var headerClicked = evt.currentTarget;
var relatedDiv = headerClicked.nextElementSibling;
var collapseMark = headerClicked.firstChild;
var isCollapsed = collapseMark.innerText[0] == "+";
collapseMark.innerText = isCollapsed ? "- " : "+ ";
relatedDiv.setAttribute("style",
isCollapsed ? "" : "display: none");
}

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 ...