user3334871
user3334871

Reputation: 1361

How do I stop a window.unload event

I have two function in my JQuery that act on a user leaving the page. The idea is that if a user leaves the page by closing the browser, we use:

$(window).bind('beforeunload', function() {
   return "Are you sure you want to leave this page without saving or submitting?";
 });

Now, we want to ask the user if they would like to save their progress only if they log out of the page, using:

$("#logoutButton").click(function(e) {
  var result = confirm("Would you like to save before logging out?");

  if(result == true) {
     $("#savebutton").click(); //simulate a click on save before redirecting
  }

  window.location.href = "www.redirectPage.com";  //go to logout page regardless of choice
});

Now, the problem that I am facing, is that whenever the user clicks logout, it performs the save check correctly, but it still asks the user if they want to leave the page, using the beforeunload method. Is there a way to stop beforeunload from triggering in this case from inside the logoutbutton click function?

Upvotes: 0

Views: 262

Answers (1)

elixenide
elixenide

Reputation: 44831

You can use .unbind() to remove all event handlers for a given event. In your code, that would be

$(window).unbind('beforeunload');

Call it right after saving:

$("#logoutButton").click(function(e) {
    var result = confirm("Would you like to save before logging out?");

    if(result == true) {
        $("#savebutton").click(); //simulate a click on save before redirecting
        $(window).unbind('beforeunload');
    }

    window.location.href = "www.redirectPage.com";  //go to logout page regardless of choice
});

Upvotes: 1

Related Questions