JSFiddle - React, Tailwind, and code Playground

HTML

<div id="container1">
<div id="box">box</div>
<div id="before" onclick="$('#box').FQP($(this),$(this).next());">before</div>
<div id="top" onclick="$('#box').FQP($(this),$(this).next());">top</div>
<div id="mid" onclick="$('#box').FQP($(this),$(this).next());">mid</div>
<div id="bottom" onclick="$('#box').FQP($(this),$(this).next());">bottom</div>
<div id="after" onclick="$('#box').FQP($(this),$(this).next());">after</div>
</div>
<div id="container2">
<div id="stats">
    <label id="boxStats"></label> |
    <label id="beforeStats"></label> |
    <label id="midStats"></label><br/>
    <label id="topStats"></label> |
    <label id="bottomStats"></label> |
    <label id="afterStats"></label>
</div>
</div>

CSS

#bounds{
    height: 100px;
    overflow-x: scroll;
}
#box{
    width:30px;
    height:20px;
    border:2px solid blue;
}

#before, #after{
    border:2px solid green;
    height:600px;
    width:40px;
    margin: 20px 0 20px 40px;
}

#top,#mid,#bottom{
    height:300px;
    width:40px;
    margin: 20px 0 20px 40px;
}

#top {
    border:2px solid red;
}

#mid {
    border:2px solid cyan;
}

#bottom {
    border:2px solid grey;
}

.fixed {  
    position: fixed;   
    top: 20px;  
    margin-left: 130px;  
    background-color: #0f0 ! important; 
}  

#container1{
    float:left;
}

#container2{
    border:2px solid lime;
    position: fixed;   
    top: 20px;  
    margin-left: 130px;  
    background-color: #0f0 ! important;
}

JavaScript

(function($){
    var FQP = function($this,top,bottom){
        topy = top.offset().top;
        boty = bottom.offset().top;
        pagey = $(window).scrollTop();
        win2y = ($(window).height()/2);
        ymax = Math.max(win2y+pagey, topy);
        y = Math.min(ymax, boty);
        $this.css({
            "position": "absolute",
            "top": y
        });
        $("#boxStats").html("topy:"+topy);
        $("#beforeStats").html("boty:"+boty);
        $("#midStats").html("win2y:"+win2y);
        $("#topStats").html("pagey:"+pagey);
        $("#bottomStats").html("Math.max("+(win2y+pagey)+", "+topy+"):"+ymax);
        $("#afterStats").html("boxTop(y):"+y);
    }
    $.fn.FQP = function(top,bottom){
        $this = this;
        FQP($this,top,bottom);
        $(window).scroll(function(){
            FQP($this,top,bottom);});
        return this;
    }
})(jQuery);

$(function(){
    $("#box").FQP($("#top"),$("#bottom"));
});

 $(function(){
  // check where the shoppingcart-div is
  var offset = $('#container2').offset();

  $(window).scroll(function () {
    var scrollTop = $(window).scrollTop(); // check the visible top of the browser
     //alert('#container2 offset:'+offset.top);
     //alert('window.scrollTop:'+$(window).scrollTop());

     if (offset.top<scrollTop) $('#container2').addClass('fixed');
    else $('#container2').removeClass('fixed');
   });
 });