Hello, learning javascript.
This code is supposed to handle different functions when the window onloads.
In the code initOne, initTwo and initThree are functions.
:Questions:
Don't really see how window.onload can store functions?
It seems to be more of an event.
And if it is an event, why is it that the functions stored in the oldOnload variable are not executed the scond time the addOnLoad function is called in line 2?
Also, how can oldOnload be a conditional if it only seems to be an array of functions? ---->*if (oldOnload) {}
Code:
addOnLoad(initOne);
addOnLoad(initTwo);
addOnLoad(initThree);
function addOnLoad(newFunction){
var oldOnload = window.onload;
if(typeof oldOnload =="function"){
window.onload = function() {
if (oldOnload) {
oldOnload();
}
newFunction();
}
}
else{
window.onload = newFunction;
}
}
ok I just read that quirksmode. the traditional way is window.onload= ...
I guess if you need more than one onload function than try this:
Code:
function onWinload(){
this.functions=new Array();
this.attachEvent=function(f){
this.functions[this.functions.length]=f;
}
this.eventTriggered(){
var i = 0;
while(i<winLoader.functions.length){winLoader.functions[i]();i++}
}
}
var winLoader=new onWinLoad(); // declare globally because trigger window load event
// changes the this contect. there are other ways but can't be bothered to look it up now
window.onload=winLoader.eventTriggered
winLoader.attachEvent(firstFunctionForOnload);
winLoader.attachEvent(secondFunctionForOnload);
onWinload is the object defenition to store all the functions in that will get called on windows load. And call them when the event is triggered
onWinload.attachEvent will add a function to the list of functions to be called
onWinload.eventTriggered will be called by the onload event of the window and in turn will call all the functions that have been added with the onWinload.attachEvent function.
You actually need only one instance so you can declare winLoader also like this:
Code:
var winLoader {
functions: new Array(),
attachEvent: function(f){
this.functions[this.functions.length]=f;
},
eventTriggered: function(){
var i = 0;
while(i<winLoader.functions.length){winLoader.functions[i]();i++}
}
} // global var, means you cannot declare this within a function it has to be available for all script in the document
window.onload=winLoader.eventTriggered; // attach winLoader.eventTriggered to the window.onload event (this function will be called when the window loads)
winLoader.attachEvent(firstFunctionForOnload);// add functions you want the winLoader to call when the window loads
winLoader.attachEvent(secondFunctionForOnload);// add another function
Last edited by amsterdamharu; 05-23-2010 at 01:19 AM.
Bookmarks