Best practice for warning user about data loss

I have a website that uses a lot of JavaScript (mostly jQuery), and I need a good global way to tell the user that they will lose unsaved changes when they move from a specific page.

At the moment, I have an onchange event hosted on the inputs, and am completing the main navigation in a function that will display a warning when clicked.

This seems awkward and does not scale well (navigation that is not part of the main navigation needs to be manually wrapped, which is far from ideal)

+7
javascript jquery user-interface
source share
3 answers

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

Then I use the 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.'; } } 
+5
source share

You are looking for the onbeforeunload event.

as

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

Native

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

This, of course, is simply a "prevention method." You still need logic to know if there have been changes to your site. This is easy to do, for example, using boolean . In addition, you should do a quick detection, for example

  if('onbeforeunload' in window){} 

I think that all major browsers support this event these days, but there is still a browser that does not know this event. Therefore, if the above condition fails, you can still retreat to another path.

+5
source share

Use the on unload window event to catch when the page changes. Then run the warning lightbox warning to alert the user that if any unsaved data is deleted.

0
source share

All Articles