JQuery.scrollTop not scrolling properly

So I have the following code:

$(document).ready(function(){
  if(window.location.hash) {
    $('body,html').animate({
      scrollTop: $(window.location.hash).offset().top
    }, 1000);

  }
})

      

Which I created with code taken from StackOverflow. I am calling the page in url#destination

, so it should actually scroll to the element whose ID is the Hash page. The element exists and the page scrolls down, but not to the exact offset of the element, but slightly higher. It might be pretty good, but I want it to work as I expected.
So now I am showing the console results:

>>>$("body").scrollTop()
>1155

>>>$("#aboutus").offset().top
>1672.890625

      

Can anyone explain this to me? Because I can't understand anything here.

+3


source to share


1 answer


Hmmm ... This works great for me. Perhaps the problem is that, as the user pointed out in the comments, the items have not been loaded yet, so you should use $(window).load()

. But if you use that, your code won't work fine as browsers have a built-in method that, when a hash exists in the url, goes directly to where the element whose id is the hash. This is because this activity is triggered before the .load event is detected in your javascript code. So, if you want to make sure the code works, replace targeting the element with a different attribute, like this:

$(window).on("load", function(){
  if(window.location.hash) {
    setTimeout(function(){
      $('body,html').animate({
        scrollTop: $('*[idt="'+(window.location.hash).replace("#", "")+'"]').offset().top
      }, 1000);
    }, 130)


  }
})

      



This is to completely make sure the animation is working correctly as there is no element that has received such a hash and the js code is handled the same way.

+3


source







All Articles