user3130007 user3130007 - 2 months ago 8x
CSS Question

How to always scroll to bottom?

I want the scroll scroll down to the bottom when add some text to the div.
This is my code. I can't find why it's not work.

<!DOCTYPE html>
<meta charset="utf-8">
window.onload = () => {
const add = document.getElementById('add');
const c = document.getElementById('content');
add.addEventListener('click', () => {
c.innerHTML += '<p>aaaaa</p>';
c.scrollTop = c.scrollHeight;
<button id="add">add</button>
<div id="content">


I'd suggest using scrollIntoView method.

So instead of c.scrollTop = c.scrollHeight; just do c.scrollIntoView(false);.

The solution you tried (c.scrollTop = c.scrollHeight;) does not work because you append elements into the div dynamically. I mean such solution is a one-time deal. If you change the content, you will have to re-execute scrolling.

Besides that, you can do the following trick using window.scrollTo method:

window.scrollTo(0, c.scrollHeight);