remind users when they leave the page

When a use visits a web page and enter some information into a form, he may intentionally or unintentionally leave the page without clicking on the submit button. It is a good usability effort to remind the user of the possible changes that have happened.

We can use a javascript to implement this.

/** checkChange.js **/ 

var alertLeavingPage = false; /* flag to turn on the alert */
var pageInputChanged = false; /* the flag of changes made */

// The onbeforeonload is called before the page is changed. It is not a standard
// method. But it is supported by IE and FF.
window.onbeforeunload = function(theEvent) {
   if (pageInputChanged == true && alertLeavingPage == true) {
      if (typeof theEvent == 'undefined') {
         theEvent = window.event;
      }
      if (theEvent) {
         theEvent.returnValue = "You have made some changes on this page, please click OK to discard the changes or Cancel to stay on the page.";
      }
   } else {
      return;
   }
}

/*
 * The method should be called on the page where the change needs to be tracked.
 * The form ID needs to be provided so the change event can be registered on certain form elements.
 */
function trackChange(formId) {
   var formElem = document.getElementById(formId);
   if (formElem) {
      for (var i=0; i<formElem.elements.length; i++) {
         var inputElem = formElem.elements[i];
         if (inputElem.type) {
            var inputType = inputElem.type.toLowerCase();
            if (inputType == 'text' || inputType == 'radio' ||
                inputType == 'checkbox' || inputType == 'select-one' || inputType == 'textarea') {
               inputElem.onchange = setChangedFlag;
            }
         }
      }
      // turn on the alert flag
      alertLeavingPage = true;
   }
}

/*
 * The method which is tied to a change event.
 */
function setChangedFlag(evt) {
   pageInputChanged = true;
}

Of course you will need to include this script to the web page. Besides that, you also need to call the trackChange() method to register the form elements that we want to track. So a form Id needs to be set in order to register. A sample html page look like following: 

<html>

<form id="the_form_id" action="" onsubmit="alertLeavingPage=false; /* no reminder for submission */"> 

</form> 

<script type="text/javascript">
<!– //
trackChange('the_form_id');

// –></script>

</html> 

Once they are added into the page, the user should see this prompt when they leave the page with un-submitted inputs. 

 leaving-page-prompt.gif

The method only detects whether there has been any change activity and it won't be able to tell whether there is change being made. For example, if someone checks a checkbox and unchecks it the script will think there has been change made.

This entry was posted in javascript, usability design. Bookmark the permalink.