Dynamically change URL using Push and Pop state

This practice is becoming more common throughout sites (such as Twitter and Facebook) for changing a URL within the address bar without reloading another page. One of the most common use cases, allows users to bookmark or share URLs when sites are using some type of infinite scroll or Single Page Applications (SPAs).

This is an extension of my post on Hawkee.com. A very simple example using pushState() and popstate

The two methods above are now a part of the extended Javascript History API introduced in HTML5.

At a high level, pushState() is a function and popstate is an event. Ideally pushState() is used to change the URL seen in the browser's address bar; while popstate is executed once a user hits 'Back' in their browser.

The example below will simply modify the URL of the given page. However, this method can only modify locations within the same domain.

Thanks to Stackoverflow for some of the code used here. Some browsers (Chrome thusfar), execute popstate on initial page load, so the code presented here is used to detect and circumvent that.

Sidenote: we’ll also be making use of jQuery and data attributes but, they’re not required.

<!-- example links that will not trigger a page refresh -->  
<a href="#" data-location="/inbox/12">Email Item 12</a>
<a href="#" data-location="/inbox/13">Email Item 13</a>

// when a user clicks one of our links
$('a').click(function (e) {

// Detect if pushState is available
if (history.pushState) {
history.pushState(null, null, $(this).attr('data-location')); // URL is now /inbox/N
// showMailItem(); // example function to do something based on link clicked
}

return false;
});

// Used to detect initial (useless) popstate.
// If history.state exists, assume browser isn't going to fire initial popstate.
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;

// listen to popstate events
$(window).bind('popstate', function (event) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL
popped = true
if (initialPop) return;

// showMailOverview(); // exmaple function to do something when user clicks 'Back'

});
Original post: http://hawkee.com/snippet/9940/

Originally published at seanwragg.com on May 22, 2013.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.