How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Fuxi picture Fuxi · Nov 26, 2009 · Viewed 117.3k times · Source

I'm dynamically adding rows to a table using jQuery. The table is inside a div which has overflow:auto thus causing a vertical scrollbar.

I now want to autoscroll my container div to the last row. What's the jQuery version of tr.scrollintoView()?

Answer

Abhijit Rao picture Abhijit Rao · Sep 24, 2010

This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop(); 
  var containerBottom = containerTop + $(container).height(); 
  var elemTop = element.offsetTop;
  var elemBottom = elemTop + $(element).height(); 
  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }
}