If you are looking for some help, I have created a jsFiddle with my question that you can check out here.
https://i.sstatic.net/96QyA.png
In a multiplayer game, I am attempting to utilize a yellow div
element for a chat feature.
However, I am facing an issue where the div
does not automatically scroll to display the most recent message added using the append() function.
$('#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');
});
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css");
div#chatDiv {
margin: 0 auto;
background-color: yellow;
width: 400px;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<div id="chatDiv"></div>
<p align="center">
<input id="chatInput" type="text" size="40" />
<button id="chatBtn" disabled>Send</button>
</p>
To see the issue in action, simply enter 4-5 words into the chatInput
field and click on the chatBtn
. You will notice that the bottom lines are not visible as the chatDiv
element fails to scroll down automatically.