0

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>
Panwen Wang
  • 3,573
  • 1
  • 18
  • 39
user12051965
  • 97
  • 9
  • 29

1 Answers1

0

There is two issues with your code snippet the first one comes from the height: inherit, which make your div grow with parent element, so the scroll bar you are seeing is a parent node (the first fixed height parent if any or the window object) scrollbar and not the chat one, the div or its parent have to be limited in height for it to work, also your comparaison in the toBottom function should be a >= instead of <= (The scrollTop property is the number of pixel scrolled from the top), but i recommend you something easier (you dont need to check or calculate the position if its given that all you need to is to go to the upmost bottom of the scroll) :

function toBottom() { 
  chat.scroll(0, chat.scrollHeight)
}
Mehdi Belbal
  • 523
  • 3
  • 7
  • what if the parent of the ```div``` has ```height: 470px;``` and still does not work?. Is this what by fixed height of parent you meant? – user12051965 Jul 23 '20 at 15:02