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.
To remove the hash URL, you can use the replaceState method on the history API to remove the hash location. Example: HTML.
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, "" .
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.
Window Location Href The window.location.href property returns the URL of the current page.
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
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 });
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