Dynamically change URL using Push and Pop state

Sean Wragg
Sean’s Blog
Published in
2 min readMay 22, 2013

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>

Original post: http://hawkee.com/snippet/9940/

--

--