Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ask a web user for confirmation if he really wants to leave the page?

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?

like image 430
Mukesh Yadav Avatar asked Oct 22 '10 15:10

Mukesh Yadav


1 Answers

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.

like image 55
ahsteele Avatar answered Nov 03 '22 13:11

ahsteele