ptg16476052
Hiding and Showing Content 541
19
currentNode.style.display = 'block';
}
else {
currentNode.style.display = 'none';
}
break;
}
currentNode = currentNode.nextSibling;
}
return false;
};
}
}
This JavaScript code is significantly more complex than any used previously in the book.
Take a look at the first line, which is repeated here:
window.onload = function() {
This is where the unobtrusiveness comes in. Instead of calling a function using the
onload attribute of the
anonymous function to the onload property of the window object. The code inside the
function will run when the onload event for the window is fired by the browser. Setting
up my JavaScript this way allows me to include this JavaScript on any page without
modifying the markup to bind it to an event. That’s handled here.
This is the method for binding functions to events programmatically. Each element has
properties for the events it supports. To bind an event handler to them, you assign the
function to that property. You can do so by declaring an anonymous function in the
assignment statement, as I did in this example, or you can assign the function by name,
like this:
function doStuff() {
// Does stuff
}
window.onload = doStuff;
In this case, I intentionally left the parentheses out when I used the function name. That’s
because I’m assigning the function itself to the onload property, as opposed to assigning
the value returned by doStuff() to that property.
▼
▼