How can I remove the location hash without causing the page to scroll?
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});
window.location's hash property is stupid in a couple of ways. This is one of them; the other is that is has different get and set values:
window.location.hash = "hello"; // url now reads *.com#helloalert(window.location.hash); // shows "#hello", which is NOT what I set.window.location.hash = window.location.hash; // url now reads *.com##hello
Note that setting the hash property to '' removes the hash mark too; that's what redirects the page. To set the value of the hash part of the url to '', leaving the hash mark and therefore not refreshing, write this:
window.location.href = window.location.href.replace(/#.*$/, '#');
There is no way to completely remove the hash mark once set without refreshing the page.
UPDATE 2012:
As Blazemonger and thinkdj have pointed out, technology has improved. Some browsers do allow you to clear that hashtag, but some do not. To support both, try something like:
if ( window.history && window.history.pushState ) { window.history.pushState('', '', window.location.pathname) } else { window.location.href = window.location.href.replace(/#.*$/, '#'); }