You Can Leave On One Condition

Scenario #1

The user is filling out a form on the site and accidentally clicks a link to leave the page. How do you warn the user?

Solution 1

Warning the user they are about to leave the page is a simple function in jQuery.

function pageLoad() {
    $(window).on('beforeunload', function () {             
        var c = confirm("Leaving so soon?");             
        if (c) {                 
            return true;             
        } else {
            return false;
        }
    });

If you got this far and wondered why the “Leaving so soon” text isn’t working, here’s why: most, probably all, browsers recognize any customization to the beforeunload event as a security breach. There might be a work-around for this, but I haven’t found one yet. As it stands, the default text works fine.

Scenario #2

The user is filling out a form in a Wizard, or custom multi-form, control. They accidentally click a link to leave the page. The Solution 1 code above resolves the issue, unless they are on the “Thank you” page. If the form is complete, the warning should be turned off and allow the user to leave unhindered.

Solution 2

The following code expands on Solution 1, but not that I’m coding against the Telerik Wizard control. The principals remain the same.

  1. Track what step the user is on
  2. Allow the “beforeunload” event to be handled on appropriate pages
  3. On the final step, do not handle the event.

My code looks like this:

//Instantiate your step variable
var step = 0;

function pageLoad() {
  //Get a reference to the wizard
  var wizard = $find('<%=rwEmployment.ClientID %>');
  
  //Get the current step
  var step = wizard.get_activeWizardStep().get_index();
  
  //Add the event handler
  $(window).on('beforeunload', function () {
    var c = confirm("Leaving so soon:");             
    if (c) {             
      return true;             
    } else {
      return false;             
    }
  });         

  //If this is the last step, disable the event handler
  if (step == 8) {
    $(window).off('beforeunload');         
  }     
}

The last part is the critical part. I tried to disable the event handler both before and inside the event handler. Neither of these worked.

“Before” didn’t work because Javascript is linear, so last code wins.

“Inside” didn’t work because once the handler is instantiated, any code inside the handler is ignored. Although, if you don’t include the confirm line, the handler is fired, but nothing happens and the user exits anyway. Even though you can’t control what the confirmation pop up says to the user, you have to include code to call the confirmation pop up.

What works is adding the handler for every step and then after it’s added, disable it, depending on your condition, using the “off” method.

This is what has worked for me. If you know of another solution, please share.

Leave a Reply

Your email address will not be published.