Daily Archives: 10/20/2011

onbeforeunload event is fired on click

onbeforeunload browser’s event fires when the window is about to navigate to another page or about to be closed. So why why would it fire when you click to call a JavaScript function that does neither of the two?

If your have your click setup similar to something like this:

<a href='javascript:doStuff()'>Click to do something</a>

or, if you’re using ASP.NET’s HyperLink control:

<asp:HyperLink ID="xhypMuLink" runat="server" NavigateURL="javascript:doStuff()">
   Click to do something
</asp:HyperLink>

And your “doStuff()” function doesn’t redirect or closes the window – you’d expect it just do its stuff and that’s it. But in addition to it, or rather before it onbeforeunload event fires, so if you have some code in the event handler – it will be executed, which in this case is undesirable.

Why does it happen? Continue reading →