I have a div that needs to automatically scroll to the bottom when new content is added. This is a common feature in chat applications where the user wants to see the latest messages without having to manually scroll down each time.
How can I achieve this functionality? I have tried the following code snippet, but it doesn't seem to be working as expected.
let tempCounter = 0;
var msgdiv = document.getElementById("messages");
function addContent() {
msgdiv.innerHTML +=
"Long long content " + tempCounter++ + "!<br/>";
msgdiv.scrollTop = msgdiv.scrollHeight;
}
setInterval(function() {
addContent();
}, 500)
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.h-100 {
height: 100%;
}
.flex-column {
flex-direction: column;
}
.d-flex {
display: flex;
}
.mh-100 {
max-height: 100%;
}
.chat-messages {
flex: 1;
height: 100%;
overflow: auto;
display: flex;
flex-direction: column-reverse;
}
.bg-white {
background-color: #fff;
}
.chat-messages-text {
display: flex;
justify-content: flex-start;
}
<div class="d-flex flex-column h-100">
<div class="chat-messages bg-white">
<div class="chat-messages-text" id="messages">
</div>
</div>
<div class="chat-input bg-warning ">
<textarea class="form-control" id="inputs" rows="3"></textarea>
<button type="button" onclick="addContent()" class="btn btn-primary mb-2"> Send Message </button>
</div>
</div>