Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the location hash without causing the page to scroll?

Is it possible to remove the hash from window.location without causing the page to jump-scroll to the top? I need to be able to modify the hash without causing any jumps.

I have this:

$('<a href="#123">').text('link').click(function(e) {   e.preventDefault();   window.location.hash = this.hash; }).appendTo('body');  $('<a href="#">').text('unlink').click(function(e) {   e.preventDefault();   window.location.hash = ''; }).appendTo('body'); 

See live example here: http://jsbin.com/asobi

When the user clicks 'link' the hash tag is modified without any page jumps, so that's working fine.

But when the user clicks 'unlink' the has tag is removed and the page scroll-jumps to the top. I need to remove the hash without this side-effect.

like image 346
David Hellsing Avatar asked Feb 19 '10 11:02

David Hellsing


People also ask

How do you remove hash?

To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.

What does Window location Hash do?

The hash property of the Location interface returns a string containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target. The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string, "" .

What does hash in URL mean?

In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.

What is window location href?

Window Location Href The window.location.href property returns the URL of the current page.


2 Answers

I believe if you just put in a dummy hash it won't scroll as there is no match to scroll to.

<a href="#A4J2S9F7">No jumping</a> 

or

<a href="#_">No jumping</a> 

"#" by itself is equivalent to "_top" thus causes a scroll to the top of the page

like image 128
scunliffe Avatar answered Oct 11 '22 12:10

scunliffe


I use the following on a few sites, NO PAGE JUMPS!

Nice clean address bar for HTML5 friendly browsers, and just a # for older browsers.

$('#logo a').click(function(e){     window.location.hash = ''; // for older browsers, leaves a # behind     history.pushState('', document.title, window.location.pathname); // nice and clean     e.preventDefault(); // no page reload }); 
like image 30
neokio Avatar answered Oct 11 '22 10:10

neokio