I want to remind users to save data on certain pages before navigating away from them (by clicking other links on the page) using the jquery ui dialog box. I know I need to use the onbeforeunload event to detect that a user is leaving the current page, then display the dialog. However, how do I allow navigation to continue to the selected url when the user clicks "Yes" on the dialog box, and stay on the current page when the user clicks "No"?
Thanks!
You just need to assign function with prompt to window.onbeforeunload event, e.g.:
window.onbeforeunload =
function() {
return "Please make sure your data is saved."
}
And the browser will automatically prompt the user with 2 choices: "Leave this page" and "Stay on this page"
After reading http://vidasp.net/jQuery-unload.html and Setting onbeforeunload on body element in Chrome and IE using jQuery, we hook into both window.onbeforeunload and bind to $(window).unload. Here's a jsFiddle with an example: http://jsfiddle.net/jtaylor/SqwV2
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