Using JavaScript, is there a way to update window.location.hash without scrolling the web page?
I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return.
Is this behavior possible?
The location. hash property sets or returns the anchor part of a URL, including the hash sign (#).
The window. location. hash returns a string that contains a # along with the fragment identifier of the URL. The fragment identifier of the URL starts with a # followed by an identifier that uniquely identifies a section in an HTML document.
Window location. The replace() method replaces the current document with a new one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With