onload event which then nests any further events that we require (the
onload event triggers "when an asset is loaded").
onclick event can be used via the
1 2 3
We've sort of touched on this technique of using
window element which we want to use the
In the case of our window load example, we can set
window.onload equal to a function which holds the majority of our event code. So you'd probably want something like the following:
1 2 3 4 5 6
Although the above is pretty pointless at the moment since an
alert doesn't really make use of our current system, we'll be able to make use of this soon. It's worth noting that whenever you make a function for event handling, you can also make it take a parameter and whenever an event calls the function it will pass the event itself to the variable -- this parameter is usually called "e" for event.
You don't actually have to create a "real" function to handle events this way either, you can create what is called an anonymous function or function literal, this is a function which is just used for this one-off purpose and so doesn't need a name, like so:
1 2 3
window.onload event handler function doesn't usually require further calling, it's usually simpler and more compact to use the above method. From here, we could use the same technique to utilise any of the other events - however unlike "window", not all elements are easily available in variables for access.
document.GetElementByID method, and passing it the ID of the element. This method must be used after everything has loaded properly, otherwise no element will be found as the Document Object Model has not fully formed - this is why our
window.onload routine is so important. The DOM can essentially be thought of as a big tree diagram which is created from your markup containing the different elements and showing how they are nested and related -- if this element data isn't ready, some components of the page cannot be properly utilised.
So using all this information, we could expand upon our code to create a basic box which does something
1 2 3
1 2 3 4 5 6 7 8
This script functions exactly as expected (in the majority of browsers), as can be seen in the JSFiddle below:
Inside these routines you can then utilise some of the fancy structures we've learnt about like loops, other functions, and if-statements, and you can also wire up several events to the same element if you want to create some more complex interactivity. If you're feeling like a bit of a challenge, try adapting our script to also handle the
ondblclick event which triggers on a double click.