Colin Wu Colin Wu - 4 months ago 14
jQuery Question

jQuery .on("unload", fn) not working for me

I am trying to detect when the user leaves a page. I thought the .on("unload",fn) method should do it:

$(document).ready(function(){
$(window).on("unload", function(){
alert("Goodbye!");
});
});


but it doesn't seem to work. When I navigate away from the page nothing happens. If I change the "unload" to "load", however, the alert box shows appropriately when the page loads.

Is this the right way to do what I want?

Answer

Maybe :

<script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

Taken from http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

"beforeunload" will be an event more reliable than the "unload" one, which seems to go deprecated. I also read that "beforeunload" event was more reliable when called from javascript than from jQuery

So in your case :

$(document).ready(function(){
      window.onbeforeunload = confirmExit;
      function confirmExit()
      {
        return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
      }
});