Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
<div>     <table id="my_table">         <tr id='row_1'><td>1</td></tr>         <tr id='row_2'><td>2</td></tr>         <tr id='row_3'><td>3</td></tr>         <tr id='row_4'><td>4</td></tr>         <tr id='row_5'><td>5</td></tr>         <tr id='row_6'><td>6</td></tr>         <tr id='row_7'><td>7</td></tr>         <tr id='row_8'><td>8</td></tr>         <tr id='row_9'><td>9</td></tr>     </table> </div>
like image 277
Misha Moroshko Avatar asked May 25 '10 15:05

Misha Moroshko


People also ask

How do I scroll to a specific div?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.

How can use scroll event in jQuery?

jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

How do I horizontally scroll a div using jQuery?

In jQuery, we can make any element tag move horizontally using the built-in function scrollLeft() function for scrolling the scrollbar horizontally according to either the position which is set as the parameter or without setting the position which would specify the position in pixel number of the scrollbar.


1 Answers

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.

like image 97
James Avatar answered Sep 19 '22 14:09

James