My question is similar to this one but none of the answers solve my problem: Use JQuery preventDefault(), but still add the path to the URL
When a user clicks a fragment link, I need to remove the default behaviour of jumping to the fragment but still add the fragment to the URL. This code (taken from the link) will fire the animation, and then add the fragment to the URL. However the fragment is then navigated to, which im my case breaks my site.
$("#login_link").click(function (e) {
e.preventDefault();
$("#login").animate({ 'margin-top': 0 }, 600, 'linear', function(){ window.location.hash = $(this).attr('href'); });
});
By updating the hash via location.href
, the browser automatically navigates to the pointer. e.preventDefault()
only cancels the default behaviour of the event, it does not affect other hash change methods, even if they're called from within the same event listener.
You can use history.replaceState
or history.pushState
to change the hash without jumping:
// Replaces the current history entry
history.replaceState(null, '', '#newhash');
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