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

感情迁移 提交于 2019-12-03 04:27:33

This behavior is very much possible. You should look into some of the libraries that have been developed to give you this functionality.

Really Simple History: http://code.google.com/p/reallysimplehistory/ SWFAddress: http://www.asual.com/swfaddress/

Luca Reghellin

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.

Catherine

As easy as it get

var scrollmem = $('html,body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);

Another thing you could try is changing the id of the element the hash points to temporarily. Worked for me!

function changeHashWithoutScrolling(hash) {
  var id = hash.replace(/^.*#/, ''),
      elem = document.getElementById(id)
  elem.id = id+'-tmp'
  window.location.hash = hash
  elem.id = id
}

Wanted to add a comment to Catherines answer but I don't have the rep yet -

Great solution however it wasn't working for me in Chrome as $('html').scrollTop() always returns 0 - a minor edit resolves the issue:

scrollmem = $('html').scrollTop() || $('body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);

Bas on the answer from Sunny I made this function that also avoids undefined and nulls:

    function changeHashWithoutScrolling(hash) {
        var id;
        var elem;

        id = hash.replace(/^.*#/, '');

        if (id) {
            elem = document.getElementById(id);

            if (elem) {
                elem.id = id + '-tmp';
                window.location.hash = hash;
                elem.id = id;
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!