How to disable snap jump on page load

When I find my_site.com/page.php#something , the scroll position is an element of the element containing this hashtag, not the top of the page.

Doing window.scrollTo(0, 0); does not change this fact. What can then?

EDIT: also tried to accept the accepted answer How do I disable the "jump" binding when loading a page? . Seems no longer working.

+6
jquery scroll hashtag
Nov 24 '14 at 1:29
source share
2 answers

What you need to do is save the hashtag for later use, and then delete it so that the browser cannot scroll the page.

Itโ€™s important that you donโ€™t put this part of the code in the $ () or $ (window) .load () function, since it would be too late and the browser has already moved to the tag.

 // store the hash (DON'T put this code inside the $() function, it has to be executed // right away before the browser can start scrolling! var target = window.location.hash, target = target.replace('#', ''); // delete hash so the page won't scroll to it window.location.hash = ""; // now whenever you are ready do whatever you want // (in this case I use jQuery to scroll to the tag after the page has loaded) $(window).load(function() { if (target) { $('html, body').animate({ scrollTop: $("#" + target).offset().top }, 700, 'swing', function () {}); } }); 
+11
Apr 23 '15 at 12:43 on
source share

The presence of this HTML is:

 <a href="#test">link</a> <div id="test"></div> 

You can not scroll the div element and instead scroll to the top of the window with this code:

 $("a").on("click", function(e) { e.preventDefault(); window.scrollTo(0, 0); }); 

EDIT:

You can try adding this:

 var firstVisit = true; $(window).scroll(function() { if (firstVisit) { window.scrollTo(0, 0); firstVisit = false; } }); 
+5
Nov 24 '14 at 1:33
source share



All Articles