mattalxndr
mattalxndr

Reputation: 9418

How to avoid scrolling to the top of the page when emptying window.location.hash

Why does the following code make the scroll jump to the top of the page?

window.location.hash = '' 

Is there a way to empty it without jumping to the top of the page?

Upvotes: 1

Views: 2345

Answers (2)

GAgnew
GAgnew

Reputation: 4083

window.location.hash keeps track of the current anchor position on the page. When you set it to be an anchor, the page will automatically go to that anchor. When you remove it, the page will go to 'blank' which is the top of the page!

To get around this do the following:

var scrollPosition = document.documentElement.scrollTop;
window.location.hash = '';
document.documentElement.scrollTop = scrollPosition;

Upvotes: 6

Tarwin Stroh-Spijer
Tarwin Stroh-Spijer

Reputation: 353

I came across this behaviour when a bug appeared in code I had written that was on a setInterval watching the hash.

setInterval(function(){
  var match = hash.match(/myValue=([^&]+)/);
  window.location.hash = '';
  if (match && match.length == 2) {
    $('#myDiv').val(match[1]);
    // RUN CODE
  }
}, 250);

In Chrome this code causes no problems, but in Internet Explorer and Firefox it will not let you scroll as it is always trying to scroll to the top of the page.

Of course the above code is "wrong" anyway as the clearing of the hash should only happen if a match is found. Sadly I only found this bug after checking in Firefox.

Upvotes: 0

Related Questions