JSFiddle - React, Tailwind, and code Playground

by Edward

HTML

<div id="container">
    <div id="chat">
    </div>
</div>
<button id="add">Add Message</button>
<div id="debug"></div>

CSS

#container {
    height: 200px;
    outline: 1px solid red;
    margin: 1em;
    overflow-y: auto;
}

JavaScript

$('#add').click(function() {
    var container = $('#container');
    var chat = $('#chat');
    // Container top + container height - the chat height
    // should be > 0 if at the bottom.. 
    // should be < 0 if scrolled back in history
    var distance = (container.scrollTop() + container.height())
            - chat.height();
    chat.append(
        $('<p/>').text(
            "Scroll @"+container.scrollTop()
            +" View @"+container.height()
            +" Chat @"+chat.height()
            +" Dis @"+distance)
        );
    // but we'll use -5 for some 'buffer space"
    if (distance > -5) chat[0].scrollIntoView(false);
});