Search code examples
javascriptjqueryajaxhtmlhtml5-history

html5 history navigation: popstate not triggered except on page load


Given a webapp with ajax navigation, you intend to make use of html5's history navigation.

But: binding onto the popstate event it is not triggered. Excep on page load, when it is:

If HTML5 available (it is detected correctly, demos do work as well in Chrome as FF):

// Callback
function historyChangeHandler(data) {
    console.log(data);
}

// Bind
$(window).bind('popstate', historyChangeHandler);


// Trigger
$("a").click(function(e) {
    var url = "/";
    // ...
    console.log("clicked");
    history.pushState({url: url}, "", url);
    return false;
});

What does not work:

  • The popstate callback historyChangeHandler() is NOT called when clicking on a link. That is, clicked is printed, but not the event.

What I tried:

  • Defer the pushState call with setTimeout.
  • e.preventDefault(); and return true instead of false
  • Also attach to div-s and return true

What does work:

  • historyChangeHandler() is called on page load.
  • historyChangeHandler() is called on pushing the back button.
  • historyChangeHandler() is called on pushing the forward button.
  • historyChangeHandler() if calling history.pushState({url: "/test"}, "", "/test") from the console!

Any clues I miss?


Solution

  • Why do you need the popstate event to fire? Why not just call your function?

    $("a").click(function(e) {
        var url = "/";
        // ...
        console.log("clicked");
        history.pushState({url: url}, "", url);
        historyChangeHandler({url: url});
        return false;
    });