John Main Logo

John Main

Code. Design. Hosting. Maintenance.

01
Sep '16

Quick one here, but one that it took me a while to discover so I thought I’d share it. If you want to have your script change the current address without actually navigating anywhere, you can push to the browser history using the following command:

History.pushState({}, title, url);

The latest item in the history will always display as the current URL in the address bar.

I find this particularly useful when I have a lot of dynamic elements on a page, particularly tabs and accordions.
For example if I wish to retain an opened tab across a page refresh I can use this trick to change the window location hash then use a simple script like this to switch to that tab on page load:

if (window.location.hash) {
$("a[href='" + window.location.hash + "']").tab('show');
}