JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrapper">
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<section>
<h1 class="fixontop">heading 1</h1>
content goes here.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
long paragraph.
</section>
<section>
<h1 class="fixontop">heading 2</h1>
2nd content goes here.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
long paragraph.
</section>
<section>
<h1 class="fixontop">heading 3</h1>
.
.
.
.
.
.
.
.
. .
.
.
.
.
.
3nd content goes here.
</section>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
<p>other content</p>
</div>
CSS
html, body{
padding: 0;
margin: 0;
}
section{
clear: both;
background: #eaeaea;
min-height: 300px;
}
section h1{
margin: 0;
}
.heading-fixed{
position: fixed;
top: 0; left: 0;
background: #cacaca;
width: 100%;
}
.hidden{
display: none;
}
JavaScript
var scrollTimeout;
var activeHeading;
var breakpoints = [];
function fix_heading(heading){
if( heading.hasClass('heading-fixed'))
return
heading
.addClass('heading-fixed')
.parents('section').css('padding-top', heading.height())
}
function unfix_heading(heading){
if(! heading.hasClass('heading-fixed'))
return
heading
.removeClass('heading-fixed')
.parents('section').css('padding-top', 0);
}
function fix_headings(breakpoints){
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(function(){
$(breakpoints).each(function(){
var breakpoint = this;
var breakpoint_heading = $('.fixontop[data-fix-on='+breakpoint+']')
if(document.body.scrollTop > breakpoint ){
fix_heading(breakpoint_heading)
}
if(document.body.scrollTop < ( breakpoint )){
unfix_heading(breakpoint_heading)
}
if(document.body.scrollTop > (breakpoint + breakpoint_heading.parents('section').outerHeight())){
unfix_heading(breakpoint_heading)
}
})
}, 0)
}
$(function(){
$('.fixontop').each(function(){
breakpoints.push ($(this).position().top)
$(this).attr('data-fix-on', $(this).position().top)
})
$(document).scroll(function(){fix_headings(breakpoints)})
})