cjmling
cjmling

Reputation: 7278

Make the scrollbar fixed to bottom even while appending content to it

For better understanding I am trying to implement chatbox with smooth transition of previous (upper) chat messages.

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

When I click "Add" I want all the number 1 - 9 slide up and append 10-12 below it.

Or in other word I want the scrollbar always scrolled fix at bottom.

I know that I can reposition the scrollbar after appending but then I will not able to see sliding animation.

Code Reference

$(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;
}

Upvotes: 2

Views: 2785

Answers (1)

lukas.pukenis
lukas.pukenis

Reputation: 13597

    $(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);
            });        
        });
    });

Do a callback to show() which will scrollTop() to the $('.chat-list')[0].scrollHeight.

If you want to have an animation then just animate scrollTop property:

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

Upvotes: 5

Related Questions