0

I try to scroll the div of a chat down with JavaScript to the newest message when the user opens the chat, sends or receives a message. For this I tried to use ScrollTop like recommended in many google search results. I made the div element as a global object because I want to use the line with ScrollTop several times in the script. The chatdiv is set to 'overflow-y: scroll;'. I verified with an alert output in the browser console that the window.onload function is working.

<script type="text/javascript">
var element_label = document.getElementById("chatdiv");

window.onload = function WindowLoad(event) {
    element_label.scrollTop = element_label.scrollHeight;
}
</script>

My next try was to get the newest message object and use ScrollIntoView on it. This also did not work.

<script type="text/javascript">
var element_label = document.getElementById("chatdiv");
var last_mess = document.getElementById("chatdiv").lastChild;

window.onload = function WindowLoad(event) {
    last_mess.scrollIntoView();
}
</script>

Am I missing a significant point or is it no longer possible to scroll a div with JavaScript?

Thanks in advance!

  • 1
    Are you sure that the `chatdiv` element is the one being scrolled? Often it is either a parent or child element that is being scrolled to show the content – Tom Nov 26 '21 at 09:29
  • I tried it with every div above the chatdiv and with body but nothing worked. – August Graf Nov 26 '21 at 15:22
  • The answer of Tho in this question (https://stackoverflow.com/questions/11715646/scroll-automatically-to-the-bottom-of-the-page) finally worked for me. – August Graf Nov 26 '21 at 15:50

0 Answers0