Notify Users Before Leaving a Page with Javascript

by Stephen Fluin 2010.05.31

Whenever you have form data, it is important that you communicate with users what is happening with this form data. The first degree of functionality that can be provided to users is notifying them when they have modified a form and they attempt to leave the page without saving the data. The further degree that the user interaction can be taken to is auto-save, but here we will limit this article to user communication.

There are a lot of ways to achieve this type of user communication, and I'll just be covering one of these. The first step is to build a change detection mechanism.

var changed = false;

From there, you should hook up the page events and change detection to the forms that should be saved before leaving the page. This method currently assumes that users must submit the form and leave the page in order to save the changes.

<textarea onkeypress="changeMade(event)"></textarea> <script> function changeMade(e) { if (e && changed == false) { changed = true; document.body.onbeforeunload = function() { return "You have unsaved changes in the current article."} } } </script>

The final piece that you need to do is hook up your form submission to allow the unload of the page. You do this because the form submission is the safe way of leaving.

<form onsubmit="document.body.onbeforeunload = null;">

With those changes, your users will now be alerted before attempting to leave the page with unsaved data, hopefully saving your content from certain destruction.
permalink