views:

72

answers:

3

Hello! Is there a way to kill the unload function with javascript(jquery)?

I am looking for something like this:

window.onbeforeunload = function(){
    confirm("Close?")
}

or in jquery:

$(window).unload(function() {
    confirm("close?")
});

Now, on window unload I get my confirm alert but it will continue in any case. Clicking cancel it won't stay on my page. Can U help me plz?

+3  A: 
$(window).unload(function() {
    var answer = confirm("Leave This website?")
if (answer){
    return false;
}
else{
    alert("Thanks for sticking around!");
    return true;
}
});
c0mrade
should not always return false.. only if user confirms...
Gaby
in this way, id does exactly the opposite of the user's choice...
oezi
@oezi he should reverse it then and matter solved :D
c0mrade
A: 

Yes, there is a way. The onbeforeunload function works a bit differently than other events. All you have to do is return a string from the function, and the browser will do the rest of the work for you. The syntax is like this:

window.onbeforeunload = function () { 
  return "Close?"; 
}

And that's all that you need to do. Clicking "Cancel" in the dialog that comes up will keep the user on the current page, and OK will let the user navigate away or close the page. It's really easy enough that you don't need to use jQuery at all.

Chibu
uhh ... no. I think you mean, `return confirm("Close?");`
Pointy
Nope, I meant exactly what I wrote. Though, I suppose I did leave out a little bit. Though it's not a spec event, it is used by most browsers. Feel free to take a look at their reference pages:Microsoft: http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspxand Mozilla: https://developer.mozilla.org/en/DOM/window.onbeforeunload
Chibu
+2  A: 

the function has to return false to abort or true to continue, so you cauld simply return the confirm like this:

window.onbeforeunload = function(){
   return confirm("Close?")
}
oezi