JSFiddle - React, Tailwind, and code Playground

by Kheema Pandey

HTML

<div id="comments">
  <ol>
    <li>Here be the comments from visitors...</li>
    <li>etc...</li>
  </ol>
</div>

<div id="commentWrapper">
  <div id="comment">
  Some text will appear here
  </div>
</div>

CSS

#commentWrapper {
  left: 450px;
  position: absolute;
  margin-left: 35px;
  width: 280px;
}

#comment {
  position: absolute;
  top: 0;
  /* just used to show how to include the margin in the effect */
  margin-top: 20px;
  border-top: 1px solid purple;
  padding-top: 19px;
}

#comment.fixed {
  position: fixed;
  top: 0;
}

JavaScript

$(document).ready(function () {
  var top = $('#comment').offset().top - parseFloat($('#comment').css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('#comment').addClass('fixed');
    } else {
      // otherwise remove it
      $('#comment').removeClass('fixed');
    }
  });
});