user3130007 user3130007 - 4 months ago 12
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>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.onload = () => {
const add = document.getElementById('add');
const c = document.getElementById('content');
add.addEventListener('click', () => {
c.innerHTML += '<p>aaaaa</p>';
c.scrollTop = c.scrollHeight;
});
};
</script>
</head>
<body>
<button id="add">add</button>
<div id="content">
</div>
</body>
</html>

Answer

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);