JSFiddle - React, Tailwind, and code Playground
HTML
<div id="scrollContainer">
<div>some content</div>
<div>some other content</div>
<div>some other content</div>
</div>
<button id="appendContent">Append Content</button>
CSS
#scrollContainer {
width: 300px;
height: 200px;
overflow: auto;
border: 1px solid black;
}
#scrollContainer div {
margin: 10px;
padding: 10px;
background: #eee;
}
JavaScript
var scrollContainer = document.getElementById("scrollContainer");
// Define the Mutation Observer
var observer = new MutationObserver(function(mutations) {
// Compute sum of the heights of added Nodes
var newNodesHeight = mutations.reduce(function(sum, mutation) {
return sum + [].slice.call(mutation.addedNodes)
.map(function (node) { return node.scrollHeight || 0; })
.reduce(function(sum, height) {return sum + height});
}, 0);
// Scroll to bottom if it was already scrolled to bottom
if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
}
});
// Observe the DOM Element
observer.observe(scrollContainer, {childList: true});
// ==============================
// Append content on button click
// ==============================
$(function() {
var counter = 1;
$("#appendContent").on('click', function() {
$("<div>appended content "+counter+"</div>").appendTo("#scrollContainer");
counter++;
});
});