JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div class="spacer"></div>
<div id="firstHeader">Header 1</div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div id="secondHeader">Header 2</div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
<div class="spacer"></div>
</body>
CSS
html, body {
margin: 0;
padding: 0;
border: 0;
}
.spacer {
height:200px;
background:#f00;
opacity:.5;
border-top:#d22 5px solid;
width: 100%;
}
#firstHeader {
background:#00f;
opacity:1;
height: 100px;
width: 100%;
z-index:500;
}
#secondHeader {
background:#0f0;
opacity:1;
height: 100px;
width: 100%;
z-index:500;
}
JavaScript
function scrollFunction() {
var sticky1 = $('#firstHeader');
var sticky2 = $('#secondHeader');
sticky1.css({
position: "static",
top: 0
});
sticky2.css({
position: "static",
top: 0
});
$('body').css({
"padding-top": 0
});
var topOffset1 = sticky1.offset().top;
var topOffset2 = sticky2.offset().top;
var stickyHeight1 = sticky1.outerHeight();
var stickyHeight2 = sticky2.outerHeight();
var scrollHeight = $(window).scrollTop();
if (topOffset1 <= scrollHeight && scrollHeight < topOffset2 - stickyHeight1) {
sticky1.css({
position: "fixed",
top: 0
});
sticky2.css({
position: "static",
top: 0
});
$('body').css({
"padding-top": stickyHeight1
});
} else if (scrollHeight >= topOffset2 - stickyHeight1 && scrollHeight < topOffset2) {
sticky1.css({
position: "fixed",
top: -(scrollHeight - (topOffset2 - stickyHeight1))
});
sticky2.css({
position: "fixed",
top: stickyHeight1 - (scrollHeight - (topOffset2 - stickyHeight1))
});
$('body').css({
"padding-top": stickyHeight1 + stickyHeight2
});
} else if (scrollHeight >= topOffset2) {
sticky1.css({
position: "static"
});
sticky2.css({
position: "fixed",
top: 0
});
$('body').css({
"padding-top": stickyHeight2
});
} else {
sticky1.css({
position: "static",
top: 0
});
sticky2.css({
position: "static",
top: 0
...