简体   繁体   中英

Chat box scroll down new messages

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>

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM