Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }
});
like image 415
Sam Quayle Avatar asked May 25 '12 15:05

Sam Quayle


4 Answers

Tag the state when you call pushState(), then ignore all popstate events that don't have your tag. e.g.

history.pushState({ myTag: true }, ...)

$(window).on("popstate", function(e) {
  if (!e.originalEvent.state.myTag) return; // not my problem
  // rest of your popstate handler goes here
}

Don't forget to call replaceState at page load so that you can handle the popstate when you get back to the initial page load.

$(function() { history.replaceState({ myTag: true }); });
like image 58
Sean Hogan Avatar answered Nov 11 '22 22:11

Sean Hogan


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() {...  
like image 3
Sam Quayle Avatar answered Nov 11 '22 22:11

Sam Quayle


The best long term fix is to up-vote https://code.google.com/p/chromium/issues/detail?id=63040 to get Google to fix this. They've known they're out of compliance with the HTML5 spec for about two years now.

like image 2
Dave Avatar answered Nov 11 '22 23:11

Dave


In order to solve the initial page load as a popstate in safari and chrome browsers, we can use SetTimeOut function.

This simply works !!

  setTimeout( function() {
      window.addEventListener( 'popstate', myFunction, false );
    }, 500 );
like image 1
Thiru Avatar answered Nov 11 '22 22:11

Thiru