Method with no JavaScript required (2023)
Here's a method that doesn't require any JavaScript at all, and uses pure (Flexbox) CSS. I've explained the method in a bit more detail over here.
The trick is to put the items in a 'content' element, which is wrapped inside a column-reverse
flexbox element, which acts as the 'scroller'. Because the items are in another ('content') container, they don't get 'flipped' but instead always line up to the bottom. This, in fact, makes the scroller scrolled to the bottom whenever stuff is added.
Advantages of this method
Aside from not relying on JavaScript, a big advantage of this method is that when the user has started scrolling the list, the scroll position remains fixed to the point where the user scrolled to. This prevents annoying content-jumping when new items are added. As soon as the user scrolls back to the bottom again, the list will stay scrolled to the bottom when updated.
Demo
Note: the JavaScript in the below demo is only required for the demo itself (to add items to the list, and see what happens).
let scrollerContent = document.getElementById('scrollerContent');
document.getElementById('addItems').addEventListener('click', function() {
let newChild = scrollerContent.lastElementChild.cloneNode(true);
newChild.innerHTML = "Item " + (scrollerContent.children.length + 1);
scrollerContent.appendChild(newChild);
});
.scroller {
overflow: auto;
height: 100px;
display: flex;
flex-direction: column-reverse;
}
.scroller .scroller-content .item {
height: 20px;
transform: translateZ(0); /* fixes a bug in Safari iOS where the scroller doesn't update */
}
<div class="scroller">
<div class="scroller-content" id="scrollerContent">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
<div class="item">Item 8</div>
<div class="item">Item 9</div>
<div class="item">Item 10</div>
</div>
</div>
<br/><br/>
<button id="addItems">Add more items</button>
code
$(document).ready(function() { var chatMessagesDiv = $('#scroll'); chatMessagesDiv.scrollTop(chatMessagesDiv[0].scrollHeight); }); – Griseldagriseldis