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

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()?


Solution 1:

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());
  }
}

Solution 2:

var rowpos = $('#table tr:last').position();

$('#container').scrollTop(rowpos.top);

should do the trick!

Solution 3:

Plugin that scrolls (with animation) only when required

I've written a jQuery plugin that does exactly what it says on the tin (and also exactly what you require). The good thing is that it will only scroll container when element is actually off. Otherwise no scrolling will be performed.

It works as easy as this:

$("table tr:last").scrollintoview();

It automatically finds closest scrollable ancestor that has excess content and is showing scrollbars. So if there's another ancestor with overflow:auto but is not scrollable will be skipped. This way you don't need to provide scrollable element because sometimes you don't even know which one is scrollable (I'm using this plugin in my Sharepoint site where content/master is developer independent so it's beyond my control - HTML may change when site is operational so can scrollable containers).

Solution 4:

much simpler:

$("selector for element").get(0).scrollIntoView();

if more than one item returns in the selector, the get(0) will get only the first item.

Solution 5:

This runnable example shows how to use scrollIntoView() which is supported in all modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView#Browser_Compatibility

The example below uses jQuery to select the element with #yourid.

$( "#yourid" )[0].scrollIntoView();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p id="yourid">Hello world.</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>