Skip to content Skip to sidebar Skip to footer

Chat Box, Auto Scroll To Bottom

How to auto scroll chat box HTML:

Solution 1:

Add this to your code:

$(".msg_container_base").stop().animate({ scrollTop: $(".msg_container_base")[0].scrollHeight}, 1000);

So the submit click function looks like this:

$("#submit").click(function() {
    var data = $("#btn-input").val();
        //console.log(data);
        $('chat_log').append('<divclass="row msg_container base_sent"><divclass="col-md-10 col-xs-10"><divclass="messages msg_receive"><p>'+data+'</p></div></div></div><divclass="row msg_container base_receive"><divclass="col-md-10 col-xs-10"><divclass="messages msg_receive"><p>'+data+'</p></div></div></div>');
        clearInput();
        $(".msg_container_base").stop().animate({ scrollTop: $(".msg_container_base")[0].scrollHeight}, 1000);
});

JSFiddle DEMO

Solution 2:

I have such simple code solution: tested and it works, explanation: div has id chat-window, we use scrollTo method and inside we start from 0 and keep scroll on the chat-window bottom, how do we get to the bottom? simply using scroll Height we can get the height of chat-window, and keep the scroll down to bottom forever on chat window

JavaScript:

chatWindow = document.getElementById('chat-window'); 
var xH = chatWindow.scrollHeight; 
chatWindow.scrollTo(0, xH);

HTML:

<div id="chat-window"></div> 

Solution 3:

Since it looks like you're using JQuery, you can use the animate function to smoothly accomplish this.

$('#myMessageContainer').stop ().animate ({
  scrollTop: $('#myMessageContainer')[0].scrollHeight
});

Solution 4:

Check this fiddle. You just need to add scrollTop() to the .msg-container-base

https://jsfiddle.net/Pranesh456/w6p5b3x6/1/

Solution 5:

Very simple code which check if user is at bottom. If user is at bottom then chat page will automatically scroll with new message. and if user scroll up then page will not auto scroll to bottom..

JS code -

var checkbottom;
jQuery(function($) {
$('.chat_screen').on('scroll', function() {
    var check = $(this).scrollTop() + $(this).innerHeight() >= $(this) 
[0].scrollHeight;
    if(check) {
       checkbottom = "bottom";
    }
    else {
    checkbottom = "nobottom";
    }
})
});
window.setInterval(function(){
if (checkbottom=="bottom") {
var objDiv = document.getElementById("chat_con");
objDiv.scrollTop = objDiv.scrollHeight;
}
}, 500);

html code -

<div id="chat_con" class="chat_screen">
</div>

Post a Comment for "Chat Box, Auto Scroll To Bottom"