JQuery preventDefault (), but still adds the fragment path to the URL without going to the fragment

My question is similar to this, but none of the answers solve my problem: Use jQuery preventDefault (), but add the path to the URL

When the user clicks the link to the fragment, I need to remove the default behavior to go to the fragment, but at the same time add the fragment to the URL. This code (taken from the link) will trigger the animation and then add the snippet to the URL. However, after this, the fragment moves, which in 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'); }); }); 
+4
source share
2 answers

By updating the hash through location.href , the browser automatically jumps to the pointer. e.preventDefault() cancels the default behavior of the event; it does not affect other methods for changing the hash, even if they are called from 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'); 
+8
source

You login_link default handler for the login_link element, but you specifically set window.location.hash , and this will cause the navigation to happen. Do you actually have an anchor with the name of what you set in the hash? If not, can you describe how it breaks your site into β€œnavigation” to anchor on the page when it does not exist? This usually does not cause a problem.

0
source

Source: https://habr.com/ru/post/1402495/


All Articles