HTML and CSS Reference
In-Depth Information
This JavaScript code is significantly more complex than any used previously in the topic.
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 <body> tag to start up the JavaScript for the page, I assign an
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.
When you declare an anonymous function in an assignment state-
ment, you must make sure to include the semicolon after the clos-
ing brace. Normally when you declare functions, a semicolon is
not needed, but because the function declaration is part of the
assignment statement, that statement has to be terminated with
a semicolon, or you'll get a syntax error when the browser tries to
interpret the JavaScript.
On the next line, I declare all the variables I use in this function. JavaScript is a bit dif-
ferent from many other languages in that variables cannot have “block” scope. For exam-
ple, in most languages, if you declare a variable inside the body of an if statement, that
variable will go away once the if statement is finished. Not so in JavaScript. A variable
declared anywhere inside a function will be accessible from that point onward in the
function, regardless of where it was declared. For that reason, declaring all your variables
at the top of the function is one way to avoid confusing bugs.
Search WWH ::

Custom Search