Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for warning the user they will lose data

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)

like image 275
Toby Avatar asked Aug 13 '10 14:08

Toby


2 Answers

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.';
    }
}
like image 155
djdd87 Avatar answered Nov 08 '22 11:11

djdd87


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.

like image 44
jAndy Avatar answered Nov 08 '22 11:11

jAndy