Prevent a User Navigating Away from a Page with Unsaved Changes

On my current project we have the problem where users will often navigate away from a page without saving their changes. The users of our application are often unfamiliar with websites and therefore simply navigate away without hitting update (as you would if you’re only familiar with desktop applications).

To help avoid this problem we wanted to alert the user to unsaved changes, similar to what Gmail does when you navigate away with an unsaved message.

Confirm Navigation Popup

Most of what you’re after here is done through the beforeunload event. Binding to this event allows you to return a string which will be displayed to the user and prompt them to stay on the page or continue navigating away.

I implemented this with a very simple jQuery extension.

$.fn.extend({
  trackChanges: function() {
    $(":input", this).keyup(function() {
      $(this.form).data("changed", true);
    });

    var form = $(this);
    $(form).submit(function() {
      form.data("submitted", true);
    });
  },
  isChanged: function() {
    return this.data("changed") && !this.data("submitted");
  }
});

$(document).ready(function() {
  if ($('.detect_changes').length > 0) {
    $('.detect_changes').trackChanges();
    $(window).on('beforeunload', function() {
      if ($('.detect_changes').isChanged()) {
        return 'Your changes have not been saved.';
      }
    });
  }
});

The only problem I ran into was that actually submitting the form would still prompt the user – this is why I needed to check the submit event and not prompt the user in that case.

Now I simply need to add the detect_changes class to any form and it will automatically prompt the user if they navigate away without saving. Happy coding.