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

Viewed 128978

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

12 Answers

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).

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.

var elem=jQuery(this);
elem[0].scrollIntoView(true);

Here is my stab at it and it's my working solution for my project.

function scrollToView($elem) {
  var $parent = $elem.parent();
  $parent.scrollTop(0);// reset parent scroll to calculate element's current position
  var viewH = $parent.height()-$elem.height();// calculate viewing pane height
  var elemTop = $elem.position().top;
  var viewMultiplier = Math.floor( elemTop / viewH); // calculate view multiplier
  $parent.scrollTop(viewMultiplier * viewH);
}
Related