jqueryajaxpjaxpopstate

How to ignore popstate initial load, working with pjax


I have been trying to get the forward an back browser buttons to work on a small site using pjax and have come up with the following code to handle class changes and fading in and out the various overlays.

However I have found that Chrome and Safari treats the initial page load as a popstate and so it is causing me grief. Is there anyway to stop this?

$(window).on("popstate", function() {
  if ($('body').hasClass('info')) {
    $('body').removeClass("info").addClass("work");
    $('.info_overlay').fadeOut(duration);
    alert('popstate');

  } else if ($('body').hasClass('work')) {
    $('body').removeClass("work").addClass("info");
    $('.info_overlay').fadeIn(duration);    

  } else {
    $('body').removeClass("project").addClass("work");
    $('.project_overlay').fadeOut(duration);
  }
});

Solution

  • I actually found the solution within pjax itself.

    Instead of doing:

    $(window).on('popstate', function() { ... 
    

    which fired the popstate on the initial page load I did:

    $(window).on('pjax:popstate', function() {...