Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there += for window.onload in Javascript?

recently I came up with the following problem:

In my web site in all html pages I call a function in body onLoad event:

<body onLoad="func1();">

This is part of my template for html, so it appears on every page in my site and I can't change that. Now, the deal is that on some pages, I need to call some other functions onload and I tried with window.onload property, but it wipes the calling of func1...

I now that I can just say:

window.onload = func2(); //where func2() calls to func1()

but this seems dirty and lame? Isn't it ?

So, is there a way to add some functions to those that are about to be executed onload, without deleting the old one? In addition I use asp.net if that could help ...

Thanks!

like image 483
anthares Avatar asked Feb 16 '10 22:02

anthares


1 Answers

You can use jQuery to chain on load handlers. Repeatedly using jQuery.load or jQuery(document).ready will chain your handlers (I believe). You other option is to do it programmatically, which means you need an auxiliary function that will chain your onload handlers for you. You can do this with a closure (or anonymous function):

var addOnLoadHandler = function(newHandler) {

    if (typeof window.onload != 'function') {
        window.onload = newHandler;
    }

    else {
        var oldHandler = window.onload;
        window.onload = function() {
            if (oldHandler) {
                oldHandler();
            }
            newHandler();
        };
    }
};

You will have to bind your functions programmatically though, so you would have to do:

addOnLoadHandlers(function() {
 alert("Hi I am the first onLoad handler!");
});

addOnLoadHandlers(function() {
 alert("Hi I am the second onLoad handler!");
});

in a javascript file (or in your html file).

Another approach is to use an array:

var onloaders = new Array();

function runOnLoads() {
    for (i = 0; i < onloaders.length; i++) {
        try {
            var handler = onloaders[i];
            handler();
        } catch(error) {
            alert(error.message);
        }
    }
}

function addLoader(obj) {
    onloaders[onloaders.length] = obj;
}

In your HTML or Javascript file you do:

addLoader(function() {
 alert("Hi I am the first onLoad handler!");
});

addLoader(function() {
 alert("Hi I am the second onLoad handler!");
});

Then in your html you can just do <body onload="runOnLoads()">

like image 139
Vivin Paliath Avatar answered Sep 21 '22 16:09

Vivin Paliath