Append content to div and scroll/animate to bottom

mowgli picture mowgli · May 27, 2012 · Viewed 45.1k times · Source

I'm trying to make a div scroll to the bottom after adding new content (using append)

Here is the main part:

$('#textdiv').append('<p>Lorem ipsum dolor sit amet, solet nostrud concludaturque no eam. Ne quod recteque pri. Porro nulla zril mei eu. Eu nibh rebum pri, eu est maiorum menandri, ridens tamquam abhorreant te eum. Ipsum definiebas ad mel.</p>');

$('#textdiv').animate({scrollTop: $('#textdiv').height()}, 1000);

See/try it in the fiddle: http://jsfiddle.net/5ucD3/7/

Very buggy.. It does not scroll to the bottom (only maybe at first few appends). When I scroll down and add new content, it scrolls up. Sometimes it does not animate at all.

How do I get it to work always? I figure I have to somehow get the correct height, but don't know how

Answer

mowgli picture mowgli · May 28, 2012

I found a way that works:

$('#textdiv').animate({scrollTop: $('#textdiv').prop("scrollHeight")}, 500);

http://jsfiddle.net/5ucD3/13/