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.

Published Saturday, November 17, 2007 12:04 AM by pluginbaby

Comments

Saturday, November 17, 2007 8:36 AM by David

# re: JavaScript onLoad event clashing

Excellent tip

Saturday, November 17, 2007 3:25 PM by Dave

# re: JavaScript onLoad event clashing

If you're using ASP.NET AJAX, $addHandler is a good way to avoid those sort of conflicts.