JavaScript onLoad event clashing

This week I had to debug some asp.net pages that has a weird behavior. They work well but each time a Js alert() raise, the hover menu are no more available (it is a classic asp:menu with dynamic hover for sub-menu).

The problem was simple: the current function attached to window.onload (which display the hover menu) was ripped by another one (which throw the alert).

Keep in mind that such line window.onload = alert('warning!'); remove the existing function attached to onload event.

To prevent this I added a new function on the Js library :

function AddOnload(funcToAdd)
{
    if (window.onload)
    {
      var currentfunc = window.onload; 
      window.onload = function()
      {
        currentfunc();
        funcToAdd();
      }
    }
    else
    {
      window.onload = funcToAdd;
    }
}

And now I call the script like this:

AddOnload(alert('warning!'));

I am sure there are plenty of ways to do this, but this worked fine for me.

No Comments