Reputation: 1714
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
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
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
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