Alexander Farber Alexander Farber - 2 months ago 7
CSS Question

How to scroll div-element acting as a chat window to its bottom?

I have prepared a jsFiddle for my question:

screenshot

I am trying to use a (yellow)

div
element for a chat in a multiplayer game.

Unfortunately, the
div
does not scroll to the most recent line that I append() to it.

JavaScript:

$('#chatBtn').button().click(function(e) {
e.preventDefault();

var str = $('#chatInput').val();
$('#chatInput').val('');
$('#chatDiv').append('<br>' + str);

var h = $('#chatDiv').attr('scrollHeight');

//$('#chatDiv').scrollTop(h);

$('#chatDiv').animate({ // DOES NOT SCROLL TO DIV BOTTOM, WHY?
scrollTop: h
}, 1000);
});

$('#chatInput').on('input', function(e) { // ENABLES/DISABLES BUTTON, WORKS OK
var str = $('#chatInput').val();
$('#chatBtn').button(str.length > 0 ? 'enable' : 'disable');
});


CSS:

div#chatDiv {
margin: 0 auto;
background-color: yellow;
width: 400px;
height: 100px;
overflow: auto;
}


HTML:

<div id="chatDiv"></div>

<p align="center">
<input id="chatInput" type="text" size="40" />
<button id="chatBtn" disabled>Send</button>
</p>


Please enter 4-5 words into
chatInput
and click the
chatBtn
each time - and you will see the problem: the bottom lines are not shown, the
chatDiv
-element is not scrolled down.

Answer

Following line is not giving height

var h = $('#chatDiv').attr('scrollHeight');

Replace above line of code with

var h =$('#chatDiv').prop('scrollHeight');

Rather than using input event you can put one condition on button click

$(document).ready(function() {
     $('#chatBtn').click(function(e) {
         e.preventDefault();   
         var str = $('#chatInput').val().trim();
          if(str !== ''){
              $('#chatInput').val('');
              $('#chatDiv').append('<br>' + str);
              var h =$('#chatDiv').prop('scrollHeight');
              $('#chatDiv').animate({
                 scrollTop: h
              }, 1000);
           }
        });
   });

If you remove input event then don't forget to remove disabled from button.

Comments