ptg16476052
544 LESSON 19: Using JavaScript in Your Pages
There are two ways to hide elements with CSS: you can set the display property to none
or the visibility property to hidden. Using the display property will hide the element
completely and remove it from the DOM. The visibility property hides the content in
the element but leaves the space it takes up empty. So for this case, using the display
property makes more sense. Every element in the document has a style property, and
that property has its own properties for each CSS property. Here’s the code that hides
each of the dd elements:
for (i = 0; i < answers.length; i++) {
answers[i].style.display = 'none';
}
The for loop iterates over each of the elements, and inside the loop, I set the display
property to none. Once the page loads, the answers will be hidden.
Traversing the Document The final step is to bind the event that toggles the display
of the answers to each of the questions. This is the most complex bit of code on the page.
First, let me explain how the event handler works:
function() {
currentNode = this.nextSibling;
while (currentNode) {
if (currentNode.nodeType == "1" && currentNode.tagName == "DD") {
if (currentNode.style.display == 'none') {
currentNode.style.display = 'block';
}
else {
currentNode.style.display = 'none';
}
break;
}
currentNode = currentNode.nextSibling;
}
return false;
};
That’s the function that will be used as the onclick handler for each of the questions. As
you may remember, in the context of an event handler, this is the element associated
with the event. The main challenge in this function is locating the answer associated with
the question the user clicked on, and displaying it.
To do so, the function will navigate through the DOM to find the next DD element
in the DOM tree following the DT element that the user clicked on. First, I use the
nextSibling property of this, and then I start a while loop that will iterate over each of
the siblings of that element. The while condition ensures that the loop will run until this
runs out of siblings.
▼
▼