12

How to auto scroll chat box

HTML:

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
<meta name="robots" content="noindex">
<title>College Enquiry Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="assets/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

<script src="assets/js/jquery-1.10.2.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        window.alert = function(){};
        var defaultCSS = document.getElementById('bootstrap-css');
        function changeCSS(css){
            if(css) $('head > link').filter(':first').replaceWith('<link rel="stylesheet" href="'+ css +'" type="text/css" />'); 
            else $('head > link').filter(':first').replaceWith(defaultCSS); 
        }
    </script>
</head>
<body>
            <div class="panel panel-primary" style="border:0px">
                <div class="panel-heading top-bar">
                    <div class="col-md-8 col-xs-8">
                        <h3 class="panel-title"><span class="glyphicon glyphicon-comment" style="margin-right:6px;"></span>College Enquiry Chat</h3>
                    </div>
                </div>


                <div class="panel-body msg_container_base">

                    <div class="row msg_container base_sent">
                        <div class="col-md-10 col-xs-10">
                            <div class="messages msg_sent">
                                <p>that mongodb thing looks good, huh?
                                tiny master db, and huge document store</p>
                            </div>
                        </div>
                    </div>

                    <div class="row msg_container base_receive">
                        <div class="col-md-10 col-xs-10">
                            <div class="messages msg_receive">
                                <p>that mongodb thing looks good, huh?
                                tiny master db, and huge document store</p>
                            </div>
                        </div>
                    </div>

                    <chat_log> . </chat_log>
                </div>

                <!--CHAT USER BOX-->
                <div class="panel-footer">
                    <div class="input-group" id="myForm">
                        <input id="btn-input" type="text" class="form-control input-sm chat_input" placeholder="Write your message here...">
                        <span class="input-group-btn">
                        <button class="btn btn-primary btn-sm" id="submit" type="submit">Send</button>
                        </span>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Javascript:

    <script>
$("#submit").click(function() {
    var data = $("#btn-input").val();
        //console.log(data);
        $('chat_log').append('<div class="row msg_container base_sent"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>'+data+'</p></div></div></div><div class="row msg_container base_receive"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>'+data+'</p></div></div></div>');
        clearInput();
});

function clearInput() {
    $("#myForm :input").each(function() {
        $(this).val(''); //hide form values
    });
}

$("#myForm").submit(function() {
    return false; //to prevent redirection to save.php
});
</script>

CSS :

.msg_container_base{
  background: #e5e5e5;
  margin: 0;
  padding: 0 10px 10px;
  max-height:80vh;
  overflow-x:hidden;
}
.top-bar {
  background: #666;
  color: white;
  padding: 10px;
  position: relative;
  overflow: hidden;
}
.msg_receive{
    padding-left:0;
    margin-left:0;
}
.msg_sent{
    padding-bottom:20px !important;
    margin-right:0;
}
.messages {
  background: white;
  padding: 10px;
  border-radius: 2px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  max-width:100%;
}
.messages > p {
    font-size: 13px;
    margin: 0 0 0.2rem 0;
  }
.messages > time {
    font-size: 11px;
    color: #ccc;
}
.msg_container {
    padding: 10px;
    overflow: hidden;
    display: flex;
}
img {
    display: block;
    width: 100%;
}
.avatar {
    position: relative;
}
.base_receive > .avatar:after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    border: 5px solid #FFF;
    border-left-color: rgba(0, 0, 0, 0);
    border-bottom-color: rgba(0, 0, 0, 0);
}

.base_sent {
  justify-content: flex-end;
  align-items: flex-end;
}
.base_sent > .avatar:after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 0;
    border: 5px solid white;
    border-right-color: transparent;
    border-top-color: transparent;
    box-shadow: 1px 1px 2px rgba(black, 0.2); // not quite perfect but close
}

.msg_sent > time{
    float: right;
}



.msg_container_base::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    background-color: #F5F5F5;
}

.msg_container_base::-webkit-scrollbar
{
    width: 12px;
    background-color: #F5F5F5;
}

.msg_container_base::-webkit-scrollbar-thumb
{
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
    background-color: #555;
}

.btn-group.dropup{
    position:fixed;
    left:0px;
    bottom:0;
}

Following code functions shows, what user input and when click on send, user will see, his sended messaged in two way.. one in sended & received form.

Is there a way to auto-scroll to bottom

Divyam Solanki
  • 461
  • 2
  • 7
  • 25
  • From the sounds of it, what you want is actually quiet simple, perhaps you could make a simple example rather than dumping a large code wall into the question. (Or, turn it into a functional snippet, that works too) – DBS Sep 27 '16 at 16:29
  • @DBS i dumped, because i have used custom way for scrollbar in chat box, and if i didn't right full code, people might think i need page to scroll. – Divyam Solanki Sep 27 '16 at 16:31
  • I don't see any custom scrollbar in the posted code, if you just mean styling, than that doesn't really affect the question. – DBS Sep 27 '16 at 16:35

6 Answers6

21

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('<div class="row msg_container base_sent"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>'+data+'</p></div></div></div><div class="row msg_container base_receive"><div class="col-md-10 col-xs-10"><div class="messages msg_receive"><p>'+data+'</p></div></div></div>');
        clearInput();
        $(".msg_container_base").stop().animate({ scrollTop: $(".msg_container_base")[0].scrollHeight}, 1000);
});

JSFiddle DEMO

NickyTheWrench
  • 3,150
  • 1
  • 23
  • 35
10

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> 
M.A.K. Ripon
  • 2,070
  • 3
  • 29
  • 47
Ilhom
  • 103
  • 1
  • 6
9

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
});
Dominic Aquilina
  • 617
  • 3
  • 13
3

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

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

Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
  • Thanks a lot @Pranesh – Divyam Solanki Sep 27 '16 at 16:47
  • This doesn't appear to work... It will always attempt to scroll to the max height of the container (which is based on screen size, not scroll), meaning once you have enough scroll to double the parents size, it stops working. You're basically just saying "scroll to " – DBS Sep 27 '16 at 17:07
  • @DBS I've the link to the fiddle, you're welcome to try. – Pranesh Ravi Sep 27 '16 at 17:13
  • I did.. after adding 5-6 messages (will vary based on screen size, just keep going and it will stop) you've scrolled to the containers max height, and it will stop working. – DBS Sep 27 '16 at 17:18
  • @DIVYAMSOLANKI **Updated the fiddle please check** – Pranesh Ravi Sep 27 '16 at 17:33
1

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>
0

Try adding these lines before starting and after ending your message appending function. It worked for me.

document.getElementById('chatbox').scrollIntoView({block: 'end', behavior: 'smooth'});

//message function

document.getElementById('chatbox').scrollIntoView({block: 'end', behavior: 'smooth'});
Parmesh
  • 34
  • 3