views:

3383

answers:

3

hi,

i'm dynamically adding rows to a table using jQuery. the table is inside a div which has overflow:auto, thus causing a vertical scrollbar.

i now want to auto-scroll my container-div to the last row - what's the jQuery version of scrollintoView(tr) ?

thx

+1  A: 

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?

William
+3  A: 
var rowpos = $('#table tr:last').position();

$('#container').scrollTop(rowpos.top);

should do the trick!

Gausie
excellent! thx!
Fuxi
+2  A: 

This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop(); 
  var containerBottom = containerTop + $(container).height(); 
  var elemTop = element.offsetTop;
  var elemBottom = elemTop + $(element).height(); 
  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }
}
Abhijit Rao
This, sir, is not just an answer, it's a solution. Thank you.
daddy6Elbows