How to scroll to specific item using jQuery?

Misha Moroshko picture Misha Moroshko · May 25, 2010 · Viewed 366.4k times · Source

I have a big table with vertical scroll bar. I would like to scroll to a specific line in this table using jQuery/Javascript.

Are there built-in methods to do this?

Here is a little example to play with.

Answer

James picture James · May 25, 2010

Dead simple. No plugins needed.

var $container = $('div'),
    $scrollTo = $('#row_8');

$container.scrollTop(
    $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);

// Or you can animate the scrolling:
$container.animate({
    scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});​

Here is a working example.

Documentation for scrollTop.