Published in


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 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:



Code, Comics, and Fhqwhgads!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store