How can I ask the user Are you sure you want to leave the page?
Like for example if you click the back button while asking a question on Stackoverflow?
The easiest way to do this is to bind an event handler to the "unload" JavaScript event. jQuery makes this very easy to do with its .unload() event handler. In the method you bind you can check to see if any the page's form fields have text input. Assuming they do pop an alert notifying the user they'll lose any unsaved data if they navigate from the page.
This method will fire an alert whenever the user navigates away from the page for any reason.
$(window).bind('beforeunload', function() {
alert('Handler for .beforeunload() called.');
});
That's obviously not very user friendly but a couple of quick modifications can make it workable to your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With