How to auto-scroll to end of div when data is added?

JavascriptJqueryHtmlCss

Javascript Problem Overview


I have a table inside of a div with the following style:

#data {
    overflow-x:hidden;
    overflow-y:visible;
    height:500px;
}

This displays a vertical scroll bar once enough data is added to the table. However, when new data is added I would like the div element to auto-scroll to the bottom.

What JavaScript code could I use to do so? I am open to options in JQuery if necessary but would prefer a JavaScript solution.

Javascript Solutions


Solution 1 - Javascript

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Solution 2 - Javascript

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDrew GalbraithView Question on Stackoverflow
Solution 1 - JavascriptVNOView Answer on Stackoverflow
Solution 2 - JavascriptValamasView Answer on Stackoverflow