I want that when the user opens that chat or writes any message, the scroll bar to go down to see the latest messages. I have found the following answer that I want to use in order to accomplish the task. https://stackoverflow.com/a/21067431/12051965
The problem is that it does not have any effect on the scroll bar, it is still at the top of the chatbox, and I would appreciate if someone could tell me what am I doing wrong.
let chat = document.getElementById("chat-messages-main-div-id");
window.onload = toBottom;
function toBottom() {
const isScrolledToBottom = chat.scrollHeight - chat.clientHeight <= chat.scrollTop + 1;
if (isScrolledToBottom) {
chat.scrollTop = chat.scrollHeight - chat.clientHeight;
}
}
.chat-messages-main-div {
width: 100%;
height: inherit;
overflow: overlay;
overflow-y: scroll;
display: flex;
flex-direction: column;
padding-left: 2%;
padding-right: 2%;
box-sizing: border-box;
padding-bottom: 15px;
}
<div id="chat-messages-main-div-id" class="chat-messages-main-div" onload="toBottom">
....
</div>