Auto-Scroll a Div to the Bottom
You can automatically scroll the content of a div to the bottom. Generally, this would be done for user convenience.
I had need for that functionality just this morning. It is the reason for this article. My thought was that some of you would appreciate knowing how to do this.
First, a div with an id is required. We'll use this one for a demonstration (contains a short list of CSS values).
inherit
initial
max−content
min−content
revert
revert−layer
unset
The demonstration div is up to an inch high. It will have scrollbars when its content is more than will fit.
Any div with an id value can be told to scroll to the bottom. The div may contain any content a div can contain. I made the demo with scrollbars and border.
Here is the source code of the demo div.
<div id="my-demo-div" style="max-height:1in; max-width:fit-content; overflow:auto; border:1px solid black; padding:.5em; border-radius:.5em;">
fit−content<br>
inherit<br>
initial<br>
max−content<br>
min−content<br>
revert<br>
revert−layer<br>
unset
</div>
So far, so good.
To get the div to scroll to the bottom automatically, this JavaScript can be used.
<script type="text/javascript">
let d = document.getElementById("my-demo-div");
d.scrollTop = d.scrollHeight;
</script>
Replace my-demo-div with the id of the div to be scrolled.
Place the JavaScript somewhere below the div to be scrolled. The scrolling will occur when the page loads.
If you prefer the scrolling to occur when the user clicks something or upon some other event, put the these two lines of JavaScript code into a JavaScript function. Then call the function when the event happens.
let d = document.getElementById("my-demo-div");
d.scrollTop = d.scrollHeight;
Only 2 lines of JavaScript are required to scroll a div automatically to the bottom.
(This content first appeared in Possibilities newsletter.)
Will Bontrager

