Forum Moderators: open
Been looking around for a proper explanation of this call to a JavaScript function.
function window::onload() basically allows me to insert the function between the opening and ending script tags, and overrides the body onload event handler (or at least carries out the event when the document body has loaded).
Can someone give me an explanation of this type of function, and some pointers to how it is handled by the DOM etc.
Many thanks,
-George
I'm guessing you have code that looks like this:
function window::onload()
{
..stuff..
}
perhaps:
window::onload = function()
{
..stuff..
}
If you wanted to assign an event handler to an element, you normally have to wait for it to be downloaded first. This syntax can be used 'inline' in the head, along with an elements id, without having to be in some kind of onload call.
function elementId::onclick(){ blah }
I haven't gone over all this to check BTW!
The 'sensible' cross-browser alternative is:
window.onload = function(){ blah }
or
window.onload = initFnfunction initFn(){ blah }
This syntax will do the same thing. This statement, and the onLoad handler in the BODY tag are mutually exclusive. Which one overrides the other depends upon which is executed last. If the JS statement is in the HEAD, then the BODY event handler will win, as it is read last.
There are ways of adding event handlers that are not mutually exclusive, and are not affected by either HTML handlers, or the 'standard' JS event handler assignment. These methods are different Standards v. IE
element.attachEvent("onclick", functionRef) //IE
element.addEventListener("click", functionRef, boolEventCapture)
There is a difference in their behaviour too. The 'dot' assignment can be used to associate any function with an element via a method name (or an event type)
element.doSomething = aFunctionfunction aFunction()
{
this.style.color = "red"
}.....
element.doSomething()
The keyword, this, refers back to the element. This still happens with addEventListener, but with attachEvent the 'context' goes back to the main window (host) - so this is largely useless.
>>know is that it's IE only
Ah it kinda makes sense to why there is little (if any) documentation on it!
>>window.onload = function(){ blah }
I thought the two were closely tied together, but, just wasn’t sure if there was a significant difference between them.
Again thanks for the explanation, appreciated.
-George