Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 220
Jonathon Watney Avatar asked Mar 14 '09 02:03

Jonathon Watney


People also ask

Which location property will give you current hash value in the URL?

The location. hash property sets or returns the anchor part of a URL, including the hash sign (#).

What is window location hash used for?

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.

What does Window location replace do?

Window location. The replace() method replaces the current document with a new one.


1 Answers

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.

like image 141
Luca Reghellin Avatar answered Sep 20 '22 04:09

Luca Reghellin