Rob Johansen
Rob Johansen

Reputation: 5164

How to get started with history.js?

I've been trying in vain for the last couple hours to learn History.js. I've created three extremely simple test files, but I can't seem to get anything working. Here are the contents of my three files.

history.html:

<!doctype html>
<html>
    <head>
        <title>History Test</title>
        <script type="text/javascript" src="jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="jquery.history.js"></script>
        <script type="text/javascript" src="history.js"></script>
    </head>
    <body>
        <a href="about.html">about</a>
    </body>
</html>

history.js:

$(document).ready(function() {
    History.Adapter.bind(window, 'statechange', handleStateChange);
});

function handleStateChange() {
    alert("State changed...");
}

about.html:

<!doctype html>
<html>
    <head>
        <title>About</title>
    </head>
    <body>
        About...
    </body>
</html>

When I click the 'about' link, why doesn't the statechange event fire or my handleStateChange() function execute?

Upvotes: 1

Views: 696

Answers (1)

Rob Johansen
Rob Johansen

Reputation: 5164

I'll answer my own question in case it helps someone else. I was under the mistaken impression that the 'statechange' event would fire anytime the browser's URL changed (e.g. clicking a link or clicking the back button). What I discovered is that 'statechange' only fires when you push something onto the History. So I updated my JavaScript to add a listener to the link...

history.js:

$(document).ready(function() {
    History.Adapter.bind(window, 'statechange', handleStateChange);
    $("#about").click(function() {
        History.pushState(null, null, "about.html");
    });
});

function handleStateChange() {
    alert("State changed...");
}

...and now I get the alert when I click the link and when I click the browser's back button.

Upvotes: 1

Related Questions