JSFiddle - React, Tailwind, and code Playground
HTML
<div class="container">
<div class="content">
<div class="item">
scroll only until end of grey CONTENT DIV
</div>
</div>
<div class="another">
<h1>Another div</h1>
</div>
<div class="more">
<h1>More content</h1>
</div>
</div>
CSS
.content {
height: 1000px;
border: 1px solid red;
background: grey;
}
.item {
position: fixed;
top: 20px;
height: 40px;
background: #fff;
width: 100%;
}
.another {
background: orange;
height: 400px;
}
.more {
background: darkblue;
height: 400px;
}
JavaScript
$(window).on("scroll", function() {
var scrollTop = $(this).scrollTop();
var containerOffset = $(".content").offset().top;
var containerHeight = $(".content").height();
var f1 = parseInt(containerHeight);
var f2 = parseInt(containerOffset);
var sum = f1 + f2;
if (scrollTop > sum - 20) {
$(".item")
.css("position", "relative")
.css("top", f1 + "px")
} else {
$(".item")
.css("position", "fixed")
.css("top", "20px");
}
});