Reputation: 1705
A visitor wants to leave the page (reload, refresh, close tab..etc.), and then a function is triggered prompting a modal "are you sure you want to leave?".
I want to allow them to leave the page without the modal prompt if they click on a link.
Here is a jsfiddle example- http://jsfiddle.net/vvj90z8h/3/
<a href="http://www.google.com" class="button">Proceed</a>
<div class="price">$139.99</div>
// function
priceFunction = function (){
window.onbeforeunload = function() {
return 'Sure you want to leave?';
}
};
// if price is 139.99, run function
var price = $(".price").text().replace(/[^0-9\.]/g, '');
if (price = 139.99){
priceFunction();
}
If you refresh the page, the modal shows, which is okay.
I'm wanting to click the link and not have the modal show.
Upvotes: 0
Views: 131
Reputation: 5668
http://jsfiddle.net/jcqjj1u3/2/
// function
priceFunction = function (){
window.onbeforeunload = function() {
return 'Sure you want to leave?';
}
};
// if price is 139.99, run function
var price = $(".price").text().replace(/[^0-9\.]/g, '');
if (price = 139.99){
priceFunction();
}
var beforeUnloadFunction;
$('.button').click(function(){
beforeUnloadFunction = window.onbeforeunload; // save the function for later just in case
window.onbeforeunload = null;
// following code is optional. Use it only if you need to do other stuff befre leaving
event.preventDefault();
// do other stuff before leaving if you'd like to
location.href= $(this).attr('href');
});
Upvotes: 0
Reputation: 207531
Set a flag when they click or unbind the event
(function(){
var pass = false;
$(document.body).on("mousedown","a.button", function () {
pass = true;
});
window.onbeforeunload = function() {
if(pass) return;
return 'Sure you want to leave?';
}
}());
or
(function(){
$(document.body).on("mousedown","a.button", function () {
$(window).off("beforeunload");
});
$(window).on("beforeunload", function() {
return 'Sure you want to leave?';
});
}());
Upvotes: 0
Reputation: 382177
You can unbind the onbeforeunload
event listener on click :
$('#proceed').click(function(){ window.onbeforeunload = null; });
Upvotes: 1