3

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.

1
  • But try returning false from the jQuery version Commented Mar 12, 2010 at 15:14

3 Answers 3

2

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?")
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

uhh ... no. I think you mean, return confirm("Close?");
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: msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx and Mozilla: developer.mozilla.org/en/DOM/window.onbeforeunload
1
$(window).unload(function() {
    var answer = confirm("Leave This website?")
if (answer){
    return false;
}
else{
    alert("Thanks for sticking around!");
    return true;
}
});

1 Comment

This leaves the page either way.. not really what he was asking for (though what he was asking for isn't possible with onunload)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.