4

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'); });

});
Community
  • 1
  • 1
Evanss
  • 23,390
  • 94
  • 282
  • 505

2 Answers2

8

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');
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • So just to be clear, replaceState will allow me to change the url to mysite.com#title without scrolling to an element with an ID of title? – Evanss Mar 20 '12 at 17:28
0

You're preventing the default handler of the login_link element from firing, but you're specifically setting window.location.hash and that will cause a navigation to happen. Do you actually have an anchor named the thing you're setting in the hash? If not, can you describe how it breaks your site to 'navigate' to an anchor on the page when it doesn't exist? Normally this does not cause a problem.

rfunduk
  • 30,053
  • 5
  • 59
  • 54
  • The anchor does exists. This is a very basic demo of my site's navigation method. The 'scrolling' is horizontal and its the position of a div, not the whole document relative to the viewport. I could make up a new fragment that doesnt relate to an element of my page. I cant think of a practical reason not too but it seemed a bit messier to me. http://smartpeopletalkfast.co.uk/pos/ – Evanss Mar 20 '12 at 17:30