How do I stop a page from unloading (navigating away) in JS?

Posted by Natalie Downe on Stack Overflow See other posts from Stack Overflow or by Natalie Downe
Published on 2009-08-19T11:53:03Z Indexed on 2010/05/03 18:48 UTC
Read the original article Hit count: 190

Does anyone know how to stop a page from reloading or navigating away?


jQuery(function($) {

    /* global on unload notification */
    warning = true;

    if(warning) {
    	$(window).bind("unload", function() { 
    		if (confirm("Do you want to leave this page") == true) {
    			//they pressed OK
    			alert('ok');
    		} else {
    			// they pressed Cancel
    			alert('cancel');
    			return false;
    		}
    	});
    }
});

I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.

However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.

In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.

If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)

Any ideas?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript