I\'m dynamically adding rows to a table using jQuery.
The table
is inside a div
which has overflow:auto
thus causing a vertical scroll
I couldn't add a comment to Abhijit Rao's answer above, so I am submitting this as an additional answer.
I needed to have the table column scroll into view on a wide table, so I added the scroll left features into the function. As someone mentioned, it jumps when it scrolls, but it worked for my purposes.
function scrollIntoView(element, container) {
var containerTop = $(container).scrollTop();
var containerLeft = $(container).scrollLeft();
var containerBottom = containerTop + $(container).height();
var containerRight = containerLeft + $(container).width();
var elemTop = element.offsetTop;
var elemLeft = element.offsetLeft;
var elemBottom = elemTop + $(element).height();
var elemRight = elemLeft + $(element).width();
if (elemTop < containerTop) {
$(container).scrollTop(elemTop);
} else if (elemBottom > containerBottom) {
$(container).scrollTop(elemBottom - $(container).height());
}
if(elemLeft < containerLeft) {
$(container).scrollLeft(elemLeft);
} else if(elemRight > containerRight) {
$(container).scrollLeft(elemRight - $(container).width());
}
}
much simpler:
$("selector for element").get(0).scrollIntoView();
if more than one item returns in the selector, the get(0) will get only the first item.
This runnable example shows how to use scrollIntoView() which is supported in all modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView#Browser_Compatibility
The example below uses jQuery to select the element with #yourid
.
$( "#yourid" )[0].scrollIntoView();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p id="yourid">Hello world.</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
$( "#yourid" )[0].scrollIntoView();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p id="yourid">Hello world.</p>
<p>..</p>
<p>..</p>
<p>..</p>
<p>..</p>
If you just want to scroll, you could use jQuery's scrollTop method. http://docs.jquery.com/CSS/scrollTop
var table = jQuery( 'table' );
table.scrollTop( table.find( 'tr:last' ).scrollTop() );
Something like that maybe?