HTML / Javascript – Setting hash without browser scrolling.

Q: I set a document’s hash using:

document.location.hash = '#my-hash';

But this always causes the browser to automatically scroll to the top of the region identified by the hash. How can I set the url’s hash without the page scrolling?


A: On newer browsers you can use the new HTML5 History API to silently set the hash by using history.replaceState(), for example:

history.replaceState(null, null, 'my-hash');

When you set the hash in this way, the page won’t scroll. To see which browsers currently support the history API, check here.