How to change the location hash without jumping in scroll position

Snippet published on January 18, 2017 by @markvaneijk in Javascript

One of the little annoyances when creating tabs with Javascript and changing the location hash depending on the activated tab, is that the page can jump in scroll position when changing the tab. Because the element ID is on the same page and changing the location hash makes the browser look for it and jump to it in scroll position.

To prevent this jumping, we can use this little workaround to have a nice user experience. It uses a method where it changes the element's ID for the active tab temporarily, then change the location hash with the new value and then change the element's ID back again so the browser won't jump to it before the location is changed.

<!-- the tab navigation -->
<ul id="Tabs">
    <li><a href="#who">Who</a>
    <li><a href="#what">What</a>
    <li><a href="#how">How</a>

<!-- the tab contents ->
<div id="who"></div>
<div id="what"></div>
<div id="how"></div>
document.addEventListener('click', function() {
    name = this.getAttribute('href').substr(1); // get id without hash
    element = document.getElementById('#'+name);

    temp = id+'-temp'; // create temporary id

    element.setAttribute('id', temp); // swap element with temporary id

    window.location.hash = id; // change hash for current location url

    element.setAttribute.attr('id', id); // set original id value back on element