views:

73

answers:

3

I have a site which uses a lot of JavaScript (mainly jQuery) and I need a nice global way to let the user know that they will lose unsaved changes when they navigate away from a particular page.

At the moment I have an onchange event placed on the inputs and wrap my main navigation in a function which will display the warning when clicked.

This feels really clunky and doesn't scale well (navigation which is not part of the main navigation needs to be manually wrapped, which is far from ideal)

+5  A: 

You are looking for the onbeforeunload event.

like

$(window).bind('beforeunload', function(){
    return "Are you really sure?";
});

native:

window.onbeforeunload = function(){
   return "Are you really sure?";
});

That of course is just the "preventing method". You still need some logic to know whether or not there were changes on your site. That could easily be done by using a boolean for instance. Furthermore you should make a quick detection like

 if('onbeforeunload' in window){}

I think all major browsers support the event nowadays, but there are still browser which don't know that event. So if the above condition fails, you can still fallback gracefully to another way.

jAndy
+1. For niceness of course, have some kind of flag you can check and only pop up the confirmation if there *are* unsaved changes that would be lost. Note that SO itself does this (start typing and answer and try to navigate away...).
Andrzej Doyle
A: 

Use on the on unload window event to catch when the page is going to change. Then prompt a lightbox alert to warn the user if navigating away any unsaved data will be lost.

Gary Green
+3  A: 

I have an onchange event on my inputs and set an isDirty variable to true when they change.

Then I use onbeforeunload event to warn the user about unsaved changes:

var isDirty = false;

window.onbeforeunload = function (evt) {
    if (isDirty) {
        return 'If you continue your changes will not be saved.';
    }
}
GenericTypeTea
why not just check if isDirty is true rather than having a seperate function to do so?
@mel33t - Erm, I am.
GenericTypeTea
You must have edited your answers because I could swear the line read "if (checkIsDirty()) {" (or something similar).
Thanks, this is so clean and can be chucked into my sites with minimal effort (the best kind of effort!)
Toby