There is a chat in which the entire message is displayed in a block with a fixed height and overflow-y: auto; It is necessary that when you open the page, in this chat the latest messages are displayed, which are located at the bottom of the block. And now, to view them, you need to scroll handles. How to solve this problem?

    1 answer 1

    You can for example use scrollTop , which will set the number of pixels that you want to back down from above. The required number of px can be found using scrollHeight

    Total:

     var chat = document.getElementById('chat'); chat.scrollTop = chat.scrollHeight; 
     .chat { overflow-y: auto; height: 100px; border: 1px solid red } .chat p { height: 2px; border: 1px solid green; } 
     <div class="chat" id="chat"> <p></p> <p></p> <p></p> <p></p> <p></p> <p></p> <p></p> <p></p> </div> 

    • <script type = "text / javascript"> var chat = document.getElementsByClassName ('chat_bottom'); chat.scrollTop = chat.scrollHeight; </ script> <div class = "content chat_bottom" id = "content"> here js pulls up the content </ div> but something doesn’t work. I'm doing through the class - Danil
    • getElementsByClassName returns the collection. If you already use it, do this: var chat = document.getElementsByClassName('chat_bottom')[0]; (with the indication of the index [0] - the first element with the chat_bottom class on the page). And not .chat_bottom , but chat_bottom (without a dot). - Alexander Igorevich
    • Already tried it anyway (I tried your code just in html, not embedded in the site, but alas, the scroll is still at the top <script type = "text / javascript"> var chat = document.getElementById ('chat'); chat. scrollTop = chat.scrollHeight; </ script> <style type = "text / css"> .chat {overflow-y: auto; height: 100px; border: 1px solid red} .chat p {height: 2px; border: 1px solid green;} </ style> <div class = "chat" id = "chat"> <p> </ p> <p> </ p> <p> </ p> <p> </ p> < p> </ p> <p> </ p> <p> </ p> <p> </ p> </ div> - Danil
    • <script type="text/javascript"> ... </script> place after html-разметки . (before </body> ), shl. It's funny, for the second day in a row I came across questions with one problem. Read the question yesterday in the comments, the problem seems to be the same. - Alexander Igorevich
    • funny, it turned out), but on the website, alas, maybe this is due to the fact that the content in the parent unit, which has overflow-y: auto; comes through js? - Danil