How can I display "Are you sure you want to leave the page?" when the user actually tries to close the page (click the X button on the browser window or tab) not when he tries to navigate away from the page (click on another link).
My client wants a message to appear when the user tries to close the page "Are you sure you want to leave the page? You still have items in your shopping cart."
Unfortunately $(window).bind('beforeunload')
doesn't fire only when the user closes the page.
jQuery:
function checkCart() { $.ajax({ url : 'index.php?route=module/cart/check', type : 'POST', dataType : 'json', success : function (result) { if (result) { $(window).bind('beforeunload', function(){ return 'leave?'; }); } } }) }
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.
You can do this by using JQuery.
For example ,
<a href="your URL" id="navigate"> click here </a>
Your JQuery
will be,
$(document).ready(function(){ $('a').on('mousedown', stopNavigate); $('a').on('mouseleave', function () { $(window).on('beforeunload', function(){ return 'Are you sure you want to leave?'; }); }); }); function stopNavigate(){ $(window).off('beforeunload'); }
And to get the Leave message alert will be,
$(window).on('beforeunload', function(){ return 'Are you sure you want to leave?'; }); $(window).on('unload', function(){ logout(); });
This solution works in all browsers and I have tested it.
Try javascript into your Ajax
window.onbeforeunload = function(){ return 'Are you sure you want to leave?'; };
Reference link
Example 2:
document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){ window.btn_clicked = true; }; window.onbeforeunload = function(){ if(!window.btn_clicked){ return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.'; } };
Here it will alert the user every time he leaves the page, until he clicks on the button.
DEMO: http://jsfiddle.net/DerekL/GSWbB/show/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With