Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Dec 2009
    Posts
    173
    Thanks
    24
    Thanked 1 Time in 1 Post

    Jquery. run script when user wants to leave the page?

    I tried this code but it didnt work.

    Code:
    $(window).unload( function () { alert("Bye now!"); } );

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,592
    Thanks
    0
    Thanked 645 Times in 635 Posts
    unload runs immediately before the page starts unloading. While a small amount of JavaScript may then run it has to be a very small amount as once the JavaScript has unloaded it can't run.

    jQuery being a rather large JavaScript is almost certain to have started unloading before the code gets far enough through to actually call the function you want to attach.

    You might consider the following instead which does the same thing without needing the jQuery library and so is more likely to still be there for long enough to run.

    window.unload = function () { alert("Bye now!"); };

    You might also want to take a look at beforeunload which will trigger and run between the decision to leave the page and the triggering of unload.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •