JQuery: scroll to center of element

I am working on a jQuery function that scrolls until a div is clicked. Right now it will scroll to the top, I was wondering if this could make it scroll to the center $('.scrollit')instead of the top, or perhaps a way to compensate for it with the number of pixels?

$(".playbox").on('click', function () {
    $('.scrollit').animate({
        scrollTop: $(this).offset().top
    }, 1000);
+4
source share
2 answers

You can use the height of the element.

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

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

+6
source

. , , . , . .

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

All Articles