How to Scroll to The Bottom of The Div

I recently needed to create a chat room, and I was faced with the task of scrolling down the div so that the user would immediately see a new message in the chat room. The chat messages, as you have already guessed, were in the div. Most programmers scroll down to the bottom of the div incorrectly, and in this article I will show you how to do it with the cleanest code possible.

First, here is the HTML code:

<div id="block">
  <p>Text</p>
  <p>Text</p>
  <p>Text</p>
  <p>Text</p>
  <p>Text</p>
  <p>Text</p>
</div>

Now I will demonstrate the CSS code that is needed to make the scroll bar appear:

div {
  height: 100px;
  overflow: auto;
  width: 200px;
}

Now let’s move on to scrolling the scroll div. Most programmers do this:

<script type="text/javascript">
  var block = document.getElementById("block");
  block.scrollTop = 9999;
</script>

Of course, this method works. But what if the div size is huge? Then the scroll bar will not go all the way to the bottom. You can, of course, set it to 99999999 or even larger, but this will look even worse. But there is a much simpler and more elegant solution:

<script type="text/javascript">
  var block = document.getElementById("block");
  block.scrollTop = block.scrollHeight;
</script>

Here, scrolling will go all the way to the bottom of the div regardless of its size, plus there are no constants right in the code that always mess it up.

And finally, it can be used not only for the div, but also for the page itself:

<script type="text/javascript">
  document.body.scrollTop = document.body.scrollHeight;
</script>

As you can see, everything is very simple. Also, this method is cross-browser, so you can safely use it.

Recommended Articles