hobbes3
hobbes3

Reputation: 30238

How to scroll a div to the bottom after appending something to that div?

So I am currently using this solution to scroll a div to the bottom by writing something like

$(document).ready(function() {
    $('#comment_list').scrollTop($('#comment_list').scrollHeight)
}

But I noticed that when I try to .append() something to #comment_list then do the above code. It doesn't actually scroll to the bottom (maybe the .scrollHeight is a static value?).

For example, this won't work

$('#comment_list').append('<div>something</div>').scrollTop($('#comment_list').scrollHeight)

Neither will this

$('#comment_list').append('<div>something</div>')
$('#comment_list').scrollTop($('#comment_list').scrollHeight)

Do I need to use some other "trick" or something?

Any tips and suggestions welcomed. Thanks in advance!

Upvotes: 2

Views: 7819

Answers (2)

0x6A75616E
0x6A75616E

Reputation: 4716

This should do the trick:

$('#comment_list').append( '<div>something</div>' );
$('#comment_list').scrollTo( '100%' );

Check this jsFiddle sample.

Source

Upvotes: 3

Sunny
Sunny

Reputation: 6346

The scrollTop function is called on $(document).ready() event.

This event is not fired when you append content to the DIV on the client-side.

So, after you append the content, you need to call the scrollTop once again to set it correctly:

$('#comment_list').append('<div>something</div>');
$('#comment_list').scrollTop('100%');

HTH

Upvotes: 0

Related Questions