Are you sure you want to move?

What is the JavaScript code / events used by sites like stackoverflow and Gmail to verify that the user is leaving the page after starting editing and trying to leave?

"Are you sure you want to navigate away from this page?" 
+6
javascript
source share
2 answers

The event used is called onbeforeunload .

 <html> <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <input id="foo"></input> <script type="text/javascript"> function unloadMessage() { return "Are you sure you want to leave?"; } function setConfirmUnload(enabled) { window.onbeforeunload = enabled ? unloadMessage : null; } $(document).ready(function() { $("#foo").keypress(function() { setConfirmUnload(true); }); }); </script> </body> </html> 
+8
source share

onbeforeunload event. Mozilla provides a useful code example. you just want to have a function that:

  • Returns a string
  • Sets e.returnValue to this line, where e is an argument or window.event.

The string will be used as your own message.

+3
source share

All Articles