JSFiddle - React, Tailwind, and code Playground

by Wexcode

HTML

<button id="prepend">Prepend an element</button>
<button id="append">Append an Element</button>

<p id="scrollTop">scrollTop: <span>0</span></p>
<p id="height">height: <span>0</span></p>

<div>
    <div class="container">
      <div>100</div>
      <div>101</div>
    </div>
</div>

CSS

body > div {
    height: 60px;
    overflow: auto;
}
.container {
    text-align: center;
    color: #fff;
}
.container > div {
    height: 40px;
    width: 30px;
    background: blue;
    border: 1px solid #000;
}

JavaScript

var $scroll    = $('body > div'),
    $container = $('.container'),
    $prepend   = $('#prepend'),
    $append    = $('#append');

var $scrollTop = $('#scrollTop span');
function updateScrollTop() {
  $scrollTop.text( $scroll.scrollTop() );
}
$scroll.on('scroll', updateScrollTop);
var $height = $('#height span')
function updateHeight() {
  $height.text( $container.height() );
}
updateHeight()

function addElement (type) {
  if (type === 'prepend') {
    method = "prependTo";
    text   = +$container.find('div:first-child').text() - 1;
  } else {
    method = "appendTo";
    text   = +$container.find('div:last-child').text() + 1;
  }
  $('<div>')[method]($container).text(text);
}

$prepend.click(function() {
  var scrollTop = $scroll.scrollTop(),
      height    = $container.height();
    
  addElement('prepend');
          
  var newHeight    = $container.height(),
      newScrollTop = scrollTop + newHeight - height;
    
  $scroll.scrollTop(newScrollTop);
  updateScrollTop();
  updateHeight();
});

$append.click(function() {
   addElement('append');
   updateScrollTop();
   updateHeight();
});