How can I prevent the browser from jumping to anchor links?
I know that I can user "return false" on the onclick event or if someone is using mootools do something like this
$('button').addEvent('click', function(e) {
e.stop()
//do blabla
});
This will stop the browser from jumping to the anchor, but I want to keep the anchor in the url so that one can share the link. I'm using the anchor actually for showing dynamic information.
Any ideas?
How can I prevent the browser from jumping to anchor links?
I know that I can user "return false" on the onclick event or if someone is using mootools do something like this
$('button').addEvent('click', function(e) {
e.stop()
//do blabla
});
This will stop the browser from jumping to the anchor, but I want to keep the anchor in the url so that one can share the link. I'm using the anchor actually for showing dynamic information.
Any ideas?
Share Improve this question asked Apr 19, 2011 at 18:06 Daniel DimitrovDaniel Dimitrov 2,01824 silver badges37 bronze badges 2- 2 The way I usually handle this is to use values after the URL hash that do not match any name or id attributes on the page. For example, "#myValue=foo" instead of "#foo". If the hash value does match an element on the page I generally expect the window to scroll to that point. – Jesse Hallett Commented Apr 19, 2011 at 18:15
- 1 Hey Jesse, I ended up doing the same. I'm setting hashes like #!something and then I just delete the ! when I want to use this hash for doing something on the page. – Daniel Dimitrov Commented Apr 25, 2011 at 8:20
2 Answers
Reset to default 5Just immediately scroll back to the top of the page.
self.scrollTo(0, 0)
I had a plugin that did this and it happened so fast I just thought anchors were broken. I don't think anyone will notice.
I haven't had a chance to test this cross-browser yet, so it might fail miserably in IE, but here's how I'm updating the URL with hash links while handling the actual action that occurs when clicking them differently (using the HTML5 history API):
var setHash = function(hash) {
// Make sure that the hash is the first character, and extract from (presumably) full URL if not
if (hash.indexOf('#') > 0) {
hash = hash.substr(hash.lastIndexOf('#'));
} else if (hash.substr(0, 1) !== '#') {
hash = '#' + hash;
}
// Add our hash element to the history/URL
if (window.history.pushState) {
window.history.pushState(null, null, hash);
} else {
window.location = hash;
}
};
$('button').addEvent('click', function(e) {
e.stop()
setHash(this.get('href'));
//do blabla
});