Newbie
Newbie

Reputation: 1714

Kill unload function in JS?

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.

Upvotes: 3

Views: 1501

Answers (3)

ant
ant

Reputation: 22948

$(window).unload(function() {
    var answer = confirm("Leave This website?")
if (answer){
    return false;
}
else{
    alert("Thanks for sticking around!");
    return true;
}
});

Upvotes: 1

oezi
oezi

Reputation: 51807

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?")
}

Upvotes: 2

Chibu
Chibu

Reputation: 1353

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.

Upvotes: 1

Related Questions