tags:

views:

188

answers:

5

Hello everyone,

I want to pop up a message asking for confirmation if the user wants to leave the current page, exactly like stackoverflow does it when you are typing a question.

Could someone help me on this, by giving me a script or redirecting me to an answer (on this site or elsewhere) ?

Thanks

+4  A: 

You could use the onbeforeunload event.

window.onbeforeunload = function() {
   return 'Are you sure that you want to leave this page?';
}
Jacob Relkin
Or try declarative syntax: http://stackoverflow.com/questions/2132760/how-to-ask-confirmation-when-closing-a-window/2132790#2132790
Ropstah
This will not work. http://jsbin.com/obizu3
SLaks
You need to return a string, not call `confirm`.
SLaks
Now, it finally will work.
SLaks
+1  A: 

You need to handle the window's onbeforeunload event and return a confirmation message as a string.

onunload will not work here. Demo

SLaks
A: 

Doesn't this work?

<body onunload="return confirm('really quit?');">

Also for framesets by the way...

Ropstah
This will not work. http://jsbin.com/obizu3
SLaks
+1  A: 

window.onbeforeunload Seems to work for IE, but something like

window.onunload = function()
{
    if (confirm('Save changes?'))
        document.forms['form1'].submit();
};

Seems to work for all browsers.

FOR
A: 

You will have to store all the values of your fields in some variables & check them whenever use changes the page url or clicks on some link, to trap the page change event use page unload event.

Page unload event link/ sample http://help.dottoro.com/ljflhicd.php.

Ravia