Location.hash takes effect only once in chrome and safari

I use location.hash to scroll to any page. It works great when the location has no hash. But this does not work if the location already has the same hash value.

For example, location.hash = 'a'; scrolls to <div id="a"></div> . Now location.href will be like http://www.example.com/test.html#a . And if location.hash = 'a'; starts again, the window will not scroll. This only happens in Chrome and Safari.

I found a solution on scrolling a page using location.hash in Safari , but I don't want to add an unnecessary tag.

And I also tried location.href = '#a' . This works fine, but I'm afraid it will reload the page. Anyone have any better ideas?

+6
source share
1 answer

It is best to replace the hash temporarily with some value that, as you know, does not exist on the page, and then reload the hash trying to gain access.

 location.hash = 'a'; // this is the function that changes the hash function setHash(newHash) { location.hash = 'someHashThatDoesntExist'; location.hash = newHash; } setHash('a'); 

That should do the trick.

+14
source

Source: https://habr.com/ru/post/899671/


All Articles