JSFiddle - React, Tailwind, and code Playground

HTML

<div id="el">
abcd
</div>

CSS

body {
  height: 10000px;
}

#el {
  position: absolute;
}

JavaScript

(function() {
    var save_scroll = 0;
      
    window.addEventListener("scroll", common);

    function common() {
      var task_win = document.getElementById("el").getBoundingClientRect(); 
      var task_win_height = document.getElementById("el").offsetHeight;
      var browser_height = document.body.clientHeight;
      var scroll_top = $(window).scrollTop();
      var task_win_top = 0;

      if (task_win.top < 1 && task_win.bottom > browser_height) {
        if (scroll_top > save_scroll) { task_win_top = task_win_top + scroll_top - save_scroll }
        if (scroll_top < save_scroll) { task_win_top = task_win_top + save_scroll - scroll_top }

        $('#el').css({"top": task_win_top});
      }
      
      console.log(task_win, scroll_top, save_scroll);
      
      save_scroll = scroll_top;
    };
})();