Scroll element into view in scrollable container

CLiown picture CLiown · Nov 20, 2013 · Viewed 25k times · Source

I have a scrolling container with a hard coded height:

.scrollingContainer {
    overflow: scroll;
    height: 400px;
}

This scrolling container contains a list of items, when I click on the item I want to scroll the container so that the item clicked is at the top of the scrolling container.

$('.scrollingContainer li a').click( function(event) {
  var vpHeight = $('.scrollingContainer').height();
  var offset = $(this).offset();
  $('.scrollingContainer').animate({
    scrollTop: vpHeight - offset.top
  }, 500);
});

Above is what I have currently, I'm having trouble with the mathematical calculation I need to perform. Also I think the var offset value is incorrect as it seems to be getting the offset from the top of the page where I was hoping to get the offset value based on it's position in the scrolling container.

Any help appreciated!

Answer

isherwood picture isherwood · Nov 20, 2013

A variation of this answer does the trick:

var myContainer = $('.scrollingContainer')

$(myContainer).on('click', 'a', function () {
  var scrollTo = $(this);

  myContainer.animate({
    scrollTop: scrollTo.offset().top - myContainer.offset().top + myContainer.scrollTop()
  });
});

Fiddle demo