Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery prompt to save data onbeforeunload

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!

like image 463
Lala Avatar asked Mar 25 '26 04:03

Lala


2 Answers

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"

like image 94
Yuriy Galanter Avatar answered Mar 27 '26 16:03

Yuriy Galanter


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

like image 41
Jamey Avatar answered Mar 27 '26 16:03

Jamey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!