How to scroll to specific item using jQuery?

How to scroll to specific item using jQuery?

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.

div {
width: 100px;
height: 70px;
border: 1px solid blue;
overflow: auto;
}

1
2
3
4
5
6
7
8
9

Solutions/Answers:

Solution 1:

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.

Solution 2:

I realise this doesn’t answer scrolling in a container but people are finding it useful so:

$('html,body').animate({scrollTop: some_element.offset().top});

We select both html and body because the document scroller could be on either and it is hard to determine which. For modern browsers you can get away with $(document.body).

Or, to go to the top of the page:

$('html,body').animate({scrollTop: 0});

Or without animation:

$(window).scrollTop(some_element.offset().top);

OR…

window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)

Solution 3:

I agree with Kevin and others, using a plugin for this is pointless.

window.scrollTo(0, $("#element").offset().top);

Solution 4:

Best plugin I found was this gist.

Related:  How do I use MS-XCEP and MS-WSTEP in .NET or JavaScript to get a certificate from AD CS?

Its not a plugin per say but it does the work of one, and it solved my problems. unfortunately it only works in FireFox. No idea why chrome doesn’t like it/doesn’t wanna run it.

EDIT: Meanwhile I managed to do it myself. No need for any plugins. Check out my gist:

// Replace #fromA with your button/control and #toB with the target to which     
// You wanna scroll to. 
//
$("#fromA").click(function() {
    $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

Solution 5:

You can use scrollIntoView() method in javascript.
just give id.scrollIntoView();

For example

row_5.scrollIntoView();

Solution 6:

I’ve always found the jQuery scrollTo plugin to be very useful for this. Play with the demos to see if it’s for you.