How to prevent jump on an anchor click?
$(document).ready(function() {
var hash = window.location.hash;
var link = $('a');
$('a').click(function(e) {
e.preventDefault();
hash = link.attr("href");
window.location = hash;
});
});
You also have to specify event argument in the function. By naming it as e
or event
and then you can manipulate it.
This is the only solution I could come up with that works consistently across all desktop and mobile browsers with various client UI libraries and frameworks. By getting the window coordinates before scrolling occurs we can revert and maintain the current scroll position.
$('a').click(function (e) {
var x = window.pageXOffset,
y = window.pageYOffset;
$(window).one('scroll', function () {
window.scrollTo(x, y);
})
});
To only prevent the "jump" you have to use different id for the target element than what is specified in the anchor.
e.g. for a link to a new tab use,
<a href="#new" />
and for the target element mask the id
<div id="new-tab"></div>
Then in your script append the mask to the real hash, and use it to get the element.
$(window).on("hashchange", function(){
var hash = this.location.hash;
var mytab = $(hash + "-tab");
});
This preserves the hash location changes in browser history that can be controlled by the back/forward buttons, and detected on page load with the hashchange
event if user enters the page with hash specified.
You should bind an onclick event to anchor and specify return false;
as a result.
The return false;
statement causes default click behaviour (jump) would not work.
You can find more info here: How to disable anchor "jump" when loading a page?