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>
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With