JSFiddle - React, Tailwind, and code Playground
by Edward
HTML
<div id="comments">
</div>
<button id="add">Add Message</button>
<button id="auto">Toggle Auto Add</button>
<div id="debug"></div>
CSS
#comments {
height: 200px;
outline: 1px solid red;
margin: 1em;
overflow-y: auto;
}
JavaScript
var n = 1;
$('#add').click(function() {
var comments = $('#comments');
// Container top + container height - the chat height
// should be == 0 if at the bottom..
// should be < 0 if scrolled back in history
var distance = (comments.scrollTop() + comments.height())
- comments[0].scrollHeight;
$('#debug').text("Scroll Top:"+comments.scrollTop()
+" Height:"+comments.height()
+" Content Height:"+comments[0].scrollHeight
+" Final:"+distance);
comments.append(
$('<p/>').text(
"Add a message " + n++
)
);
// but we'll use -2 for some "fuzz distance"
// You may want this to be higher so as to not require the EU
// to scroll ALL the way to the bottom.. like maybe half the hight of
// a chat message.. or full height of a chat message
if (distance > -2) {
comments.scrollTop(comments[0].scrollHeight);
}
});
function runIt(next) {
$('#add').click();
$('#auto').delay(500,"chat").queue("chat", runIt);
next();
}
$('#auto').data('active',0).click(function() {
var a = $(this).data('active');
if (a == 1) {
$(this).clearQueue("chat").data('active',0);
} else {
$(this).data('active',1)
.queue("chat",runIt)
.dequeue("chat");
}
});