Window onload Event
By Stephen Bucaro
The onload event executes immediately after the webpage finishes loading. You should
never write code that attempts to access elements on a document before the page
completes loading because the element may not be created yet. The onload event
allows you to access webpage elements immediately after all the coded elements have been created.
Originally the onload event was called in the body tag and it was usually used
to execute some initialization code as shown below.
Today programmer's frown on calling the onload event in the body tag because onload
is technically a window event not specifically related to the body element.
Now, the onload event is usually called near the end of a Java Script code block in
the head section of the webpage as shown below.
window.onload = init;
The problem with the above method is that it allows only one function to be called
by the onload event. The method shown below uses addEventListener which allows
you to add multiple event listeners to the onload event.
if (window.addEventListener) // Netscape/Firefox/Opera
window.addEventListener("load", function1, false);
window.addEventListener("load", function2, false);
else if (window.attachEvent) // IE
However Internet Explorer does not recognize addEventListener, it uses attachEvent
instead, and the code above shows you how to make your code compatible with both Firefox and Internet Explorer.
In the last argument of addEventListener, true means you want to use event
capturing and false means you want to use event bubbling. To make a complex
subject simple, when you execute an event on a element that is nested inside another element
(and this is always the case because all elements are nested inside the body element)
and multiple elements have event handlers for the same event, event capturing causes
the outer element to execute its event handler first, bubbling causes the inner element
to execute its event handler first. Internet Explorer supports only event bubbling.
More Java Script Code:
• The switch / case Structure
• The break Statement
• Java Script Trigonometric Methods
• Format a Number as Currency
• Java Script Math.cos Method
• Java Script Events
• Window onload Event
• Accessing Web Page Elements
• Convert a String to a Number