1

Possible Duplicate:
How to show the “Are you sure you want to navigate away from this page?” when changes committed?

Stackoverflow has a really interesting feature: if you start writing a new question, then you try to navigate away from the page, it will show an alert asking you confirm that you want to leave this page. This works whether you are typing a new address and entering it in the address bar, using the forward/back button, etc..

How does this work? I'd be interested to know less about the alert itself and more specifically about what event/code is triggering the alert.

Thanks!

Community
  • 1
  • 1
jay
  • 12,066
  • 16
  • 64
  • 103
  • window.onunload does that for you, do a google search and there should be a few million sites to choose from. – adeneo Dec 12 '12 at 10:36

4 Answers4

4

A flag is set when the textarea is amended. The flag is checked on the unload() event of the window and the alert() is displayed if required. Something like this:

var textAmended = false;
$("textarea").change(function() {
    textAmended = true;
});

$(window).unload(function() {
    if (textAmended) {
        alert('You started writing a question...');
    }
});

More information on unload()

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    I don't think it really works with the alert, is'nt it just a string returned to the unload function that triggers that confirm box ? – adeneo Dec 12 '12 at 10:39
0

This is usually done by checking the value of the textarea, input etc. and changing the window.onunload function, either by passing a string or nothing, like below:

$('textarea').change(function() {
    if( this.value == "" ) {
        window.onbeforeunload = null;
    }else{
        window.onbeforeunload = "Are you sure you want to leave?";
    }
});

That should trigger the built in confirm!

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

I think you want some confirmation on just navigating away from current window or closing it:

http://jsfiddle.net/tLWZX/

$(window).on('beforeunload', function() {
    return 'You have unsaved changes.';
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0
window.onbeforeunload = exit;
function exit() {
var t = 0;
$("textarea").each( function() {
var v = $(this).val();
if(v!="") {
t=t+1;
}
});
if(t>=1) {
return "You Have Some text written in textareas. Still you want to leave?";
}
}

what you wanted is in best and pure way!

http://jsfiddle.net/p4NPh/

Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62