8

I am working on a jQuery function that scrolls to the div on click. Right now it will scroll to the top, I was wondering if their was a way to make it scroll to the center of $('.scrollit') instead of top, or possibly a way to offset it by some pixel amount?

$(".playbox").on('click', function () {
    $('.scrollit').animate({
        scrollTop: $(this).offset().top
    }, 1000);
Tushar
  • 85,780
  • 21
  • 159
  • 179
Jeff
  • 1,018
  • 1
  • 15
  • 33
  • 1
    similar tyoe Question Answer here. http://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom i think it will be help you – Sk Asraf Jun 26 '16 at 06:22

3 Answers3

12

You can use the height of the element.

scrollTop: $(this).offset().top + $(this).height() / 2;

Add the half of the height of the element to the scrollTop to scroll to the center of the element.

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Thanks Tushar!, I ended up modding your answer a little bit to fit specific needs but it worked great! I ended up doing scrollTop: $(this).offset().top - $(this).height() Thank You! – Jeff Jun 26 '16 at 06:34
4

There are two major difference to the other answer. Its relevant if you add or remove offset, so I exchange the plus with a minus. And I use the screen size as reference and not the element. To animate the scrolling and wrap in a function is optional.

function scrollTo (id) {
   $('html,body').animate({
      scrollTop: $("#"+id).offset().top - $(window).height()/2
   }, 1000);
}
and-bri
  • 1,563
  • 2
  • 19
  • 34
0

Not sure if my use case is identical to what the question was originally asking for, but I found this question when trying to solve my case.

What I wanted to do was scroll such that vertical center of the viewport aligned with the vertical center of the target element.

The code I ended up using for this is as follows. This works by offsetting the scroll target by half of the difference between the viewport height and the element height.

Note: I think this code assumes the element is smaller than the viewport. To also handle cases where the element were larger than the viewport, you might need to modify this using an absolute value function or something. This wasn't necessary for my use case.

function scrollto (target) {
    document.documentElement.scrollTop = document.body.scrollTop = target.offset().top - (window.innerHeight - target.height()) / 2;
}
scrollto($(this));