views:

72

answers:

2

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?

+1  A: 

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 .unload() called.');
});

That's obviously not very user friendly but a couple of quick modifications can make it workable to your question.

ahsteele
how we will do if a user is editing something ?
MakDotGNU
I think you'll find the `unload` event is too late to prevent the user from leaving. You need to use the `onbeforeunload` event. Also you can't use jquery to bind to `onbeforeunload` in all browsers
rojoca
so you wanna say to use pure JavaScript instead jquery because of browser compatibility
MakDotGNU
@MakDotGNU - see the questions linked to in my answer.
rojoca
@rojoca updated to use `beforeunload`. Didn't realize `unload` was too late. Thanks for the tip.
ahsteele
+1  A: 

I think this question has what you're looking for. Which points to this even more pertinent question. And here is one more

rojoca