Using either pure Javascript or jQuery, how do I scroll the page so that the nth row in a table is centered on the page?
Some examples I've seen that have this sort of feature usually require that the element I scroll to uses an id as the selector, but since the table has a dynamic amount of rows and may be paged, I'd rather not go this route of having to give each <td>
tag an id.
Is the easiest way to just calculate the position of the td relative to the top of the document and scroll the window using setInterval until the middle of the window is >= to the position of the nth <td>
tag?
I suppose some pseudo-code of the way I imagine it working would be:
function scrollToNthTD(i) {
var position = CalculatePositionOfTR(i);
var timer = setTimeout(function () {
ScrollDownALittle();
if( CenterOfVerticalWindowPosition > position)
clearInterval(timer);
}, 100);
}
Latest update (no-jquery for for modern browsers)
var rows = document.querySelectorAll('#tableid tr');
// line is zero-based
// line is the row number that you want to see into view after scroll
rows[line].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
Demo at http://jsfiddle.net/r753v2ky/
Since you can use jQuery here it is..
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
w.scrollTop( row.offset().top - (w.height()/2) );
}
Demo at http://jsfiddle.net/SZKJh/
If you want it to animate instead of just going there use
var w = $(window);
var row = $('#tableid').find('tr').eq( line );
if (row.length){
$('html,body').animate({scrollTop: row.offset().top - (w.height()/2)}, 1000 );
}
Demo at http://jsfiddle.net/SZKJh/1/
Don't use jQuery - it slows down sites!
var elem = document.getElementById("elem_id");
elem.scrollIntoView(true);
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