Sometimes, we want to auto-scroll to end of div when data is added with JavaScript.
In this article, we’ll look at how to auto-scroll to end of div when data is added with JavaScript.
How to auto-scroll to end of div when data is added with JavaScript?
To auto-scroll to end of div when data is added with JavaScript, we can set the scrollTop of the div to the scrollHeight of the div.
For instance, we write
window.setInterval(() => {
const elem = document.getElementById("data");
elem.scrollTop = elem.scrollHeight;
}, 5000);
to call setInterval to run a function that scrolls the div with ID data to the bottom.
We get the div with getElementById.
And we set elem.scrollTop to elem.scrollHeight to scroll the div to the bottom.
Conclusion
To auto-scroll to end of div when data is added with JavaScript, we can set the scrollTop of the div to the scrollHeight of the div.