Confirmation dialog on leaving page (Javascript)

If you want to show confirmation dialog before user leaves or reloads the page, you can use Javascript onbeforeunload() event attribute. When unload event fires, it shows a prompt asking whether user wants to leave or reload the page. Most browsers will return the event string, but in some browsers such as Firefox it may not be displayed.
JS
  • 1
  • 2
  • 3
window.onbeforeunload = function(e) { return "Do you want to exit this page?"; };
Or jQuery
JQUERY
  • 1
  • 2
  • 3
$(window).bind('beforeunload', function(){ return "Do you want to exit this page?"; });

Confirmation dialog only when user enters some text

Most of the time you want to display exit dialog only when a user interacts to your webpage. Have a look at code below, here we display confirm exit dialog after user enters 10 or more characters in text-box.
JS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
<textarea name="mytext" id="mytext" cols="50" rows="5"></textarea> <script type="text/javascript"> function myfunction(text){ if(text.length > 10){ window.onbeforeunload = function(e) { return "You text is not saved!"; } } } </script>
jQuery :
JS
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
<textarea name="mytext" id="mytext" cols="50" rows="5"></textarea> <script type="text/javascript"> $("#mytext").keyup(function(){ if($(this).val().length > 10){ $(window).bind('beforeunload', function(){ return "You text is not saved!"; }); } }); </script>

Browser Support

4+1+1+3+12+
New question is currently disabled!