Can I update window.location.hash without having the web page scroll?

Jonathon Watney picture Jonathon Watney · Mar 14, 2009 · Viewed 28.5k times · Source

Using JavaScript, is there a way to update window.location.hash without scrolling the web page?

I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return.

Is this behavior possible?

Answer

Luca Reghellin picture Luca Reghellin · Mar 3, 2014

To change the hash without having the page reload/scroll, you can now simply use html5 history.pushState.

history.pushState(null,null,'#hashexample');

It's supported by all the major browsers:

http://caniuse.com/history

MDN:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method

Also note that the last url parameter we're using here, it can be any url, so it's not limited to hashes.