3

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!

Lala
  • 237
  • 1
  • 7
  • 12
  • 2
    All you can do is ask the browser to ask the user to confirm that they want to leave the page, via the "onbeforeunload" mechanism. *edit* oh wait - you're asking how you find out that they decided *not* to leave your page, right? – Pointy Jun 15 '12 at 19:47
  • @Pointy My site already uses jquery ui dialogs, so I want to use that in this case too and be able to customize the dialog. But how do I code that clicking "Yes" means to continue with the original request and "No" signals staying on the same page? – Lala Jun 15 '12 at 22:08
  • Well that's the problem. When the user clicks "No", to stay on the page, the net effect is that nothing happens - it's like the user never clicked on whatever it was that triggered the event. Thus I don't think there is any way to directly do what you want, other than perhaps to try something like adding a class to the `` in the "onbeforeunload" handler, and then having CSS respond with some change to the layout, or something. – Pointy Jun 15 '12 at 22:11

2 Answers2

3

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"

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

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

Community
  • 1
  • 1
Jamey
  • 1,595
  • 9
  • 23