6

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
  • 82,599
  • 19
  • 151
  • 169
Jeff
  • 958
  • 1
  • 12
  • 31
  • 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

2 Answers2

11

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
  • 82,599
  • 19
  • 151
  • 169
  • 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,459
  • 2
  • 17
  • 33