Make the scroll bar fixed to the bottom even when adding content to it

For a better understanding, I am trying to implement a chatbox with a smooth transition of the previous (top) chat messages.

Here is http://jsfiddle.net/eEEGE/

When I click Add, I want the whole number 1 - 9 to move up and add 10-12 below it.

Or, in other words, I want the scroll bar to always scroll the fix below.

I know that I can change the position of the scrollbar after adding, but then I can not see the moving animation.

Code Link

$(document).ready(function(){
    // set the default scroll bar to bottom of chat box
    $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
    $("button").click(function(){
        $('.chat-list li:last-child').append('10<br/>11<br/>12');
        $('.chat-list li:last-child').show('slow');     
    });
});

<ul class="chat-list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li style="display:none"></li>
</ul>
<button>add</button>

.chat-list{
    height:100px;
    overflow:auto;
}
+2
source share
1 answer
    $(document).ready(function(){
        // set the default scroll bar to bottom of chat box
        $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
        $("button").click(function(){
            $('.chat-list li:last-child').append('10<br/>11<br/>12');
// Do a callback for show()
            $('.chat-list li:last-child').show('slow', function() {
             $(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
            });        
        });
    });

Make the callback show()that will be scrollTop()on $('.chat-list')[0].scrollHeight.

, scrollTop:

$(".chat-list").animate({
    scrollTop: $(".chat-list")[0].scrollHeight
 },'slow');
+5

All Articles