22

I want to ask user whether he really want to leave the page or not, when he clicks the close button just like it done in google docs. How to do that using jquery?

Vetragon
  • 416
  • 1
  • 4
  • 9

2 Answers2

30

You set the window's onbeforeunload property to a function.

This post has a good example on how to do it.

Or another example:

<script language="JavaScript">
  var needToConfirm = true;

  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (needToConfirm)
      //return message to display in dialog box;
  }
</script>

...

<input type="Submit" value="Save" onclick="needToConfirm = false;" />


And to set needToConfirm for your form you can:

$(document).ready(function() { 
    $(':input', document.myForm).bind("change", function() { needToConfirm = true; }); // Prevent accidental navigation away
});
Vikrant
  • 4,920
  • 17
  • 48
  • 72
Prody
  • 5,182
  • 6
  • 44
  • 62
3

Following worked for me;

 $(window).unload(function() {
                if(event.clientY < 0) {
                    //do whatever you want when closing the window..
                }
            });
  • 2
    I think that 'beforeunload' event is way more useful to ask the user whether he's wants to save his changes: `$(window).bind('beforeunload', function() { ... });` – Alexis Wilke Dec 29 '13 at 11:24
  • Ah! It looks that this changed in the last few years... so in 2011 it may still have been working. – Alexis Wilke Dec 29 '13 at 11:31