Gus
Gus

Reputation: 1923

Detect URL change without hash or iteration

I have a Google-instant type thing where the URL will change via the history API. The problem occurs when the users goes from one query to another, then hits the back button, and nothing happens. The URL in the address bar changes, that's it. I need to detect when the back/forward button is hit, or when the URL changes, and fire and event. I only care about this working in modern browsers, since my site is only accessible by modern browsers anyway.

I would also prefer not to use iteration since that is not instant and is not as simple as events. Are any other methods that are more simple? Thanks.

Upvotes: 1

Views: 1174

Answers (1)

adeneo
adeneo

Reputation: 318192

the windows popstate event fires whenever the URL is changed with pushstate, and that is the event you should use to change the sites content with ajax or whatever you're using, as that also fires on the browser back / forward button. In some browsers it also fires on first pageload, so you'll need to check for that as well.

I don't really have time to write a full fledged native JS example with event handlers and what not, but here's a quick jQuery version:

var checkForFirstLoad = true;

$(window).on({
    load: function() {
        checkForFirstLoad = false;
    },
    popstate:function(e) {
        if (checkForFirstLoad) {
            updatePage(e.originalEvent.state!=null ? e.originalEvent.state.page : document.location.pathname, true);
        }else{
            checkForFirstLoad = false;
        }
    }
});

function updatePage(pageURI, type, switchContent) {
    if (!type) {
        history.pushState({ page: pageURI }, page, pageURI);
    }
    if (switchContent) {
        //replace site content etc.
    }
}

Now this is just a really simple example, and there's a lot more going on, like checking browser support, checking if the clicked link has the same href as the current url, recognizing different url's etc. I just copied this from a project with a few thousand lines of code in an object literal, so you'll have to figure out exactly how popstate works and how you use it in your own code.

Upvotes: 1

Related Questions