简体   繁体   中英

Scroll to bottom on page load

I have the following code, it's a chat display that I got using the Firebase API. The problem is that, when the page loads, I want it to directly have the scrollbar set at the bottom. At the moment it is sort of sliding slowly to the bottom (because of the .animate). How can I have the scrollbar always stay at the bottom when I reload the page, even if new content is added to the chat?

$(document).ready(function () {    
    var myDataRef = new Firebase('https://ot7fwnsj7h7.firebaseio-demo.com/');
    myDataRef.on('child_added', function (snapshot) {
        var message = snapshot.val();
        displayChatMessage(message.name, message.text);
    });

    function displayChatMessage(name, text) {
        $('<div/>').text(text).prepend($('<em/>').text(name + ': ')).appendTo($('#displayChat'));
        // make text scroll everytime someone posts
        $('#displayChat').animate({
            scrollTop: $("#displayChat")[0].scrollHeight
        }, 'slow');
    };
});

And here's my fiddle:

http://jsfiddle.net/qxkr35pj/

I hope I've been clear! Thanks.

This line of code scrolls the element to its bottom. Call it every time you update the view.

JSFiddle

$("#displayChat")[0].scrollTop =  $("#displayChat")[0].scrollHeight

I think what you want is this instead of your animate code:

$('#displayChat').scrollTop($("#displayChat").height());

You'd also want to use that every time a message gets added - it'll take the scrollbar to the bottom of the div.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM