JSFiddle - React, Tailwind, and code Playground
HTML
<p id="ab">
</p>
<div id="lp1" class="section">
</div><div id="lp2" class="section">
</div><div id="lp3" class="section">
</div><div id="lp4" class="section">
</div>
CSS
.section{
height:450px;
transition: background .4s;
}
.section:nth-of-type(2){
background:blue;
}
.active-section{
background:red!important;
}
JavaScript
var positions = [];
var activeSection = "active-section";
var lastListPoint;
var listPointIdPrefix = "#lp";
function findPositions(){
jQuery(".section").each(function(){
var positionInfo = $(this).offset().top;
positions.push(positionInfo);
});
halfWindowHeight = $(window).height()/2;
};
findPositions();
$(window).on("scroll",function(){
currentPos = window.pageYOffset;
findActiveSection();
}).scroll()
$(window).on("resize",function(){
findPositions();
})
function findActiveSection(){
var closest = null;
$.each(positions, function(){
if (this <= currentPos+halfWindowHeight && (closest == null || (currentPos+halfWindowHeight - this) < (currentPos+halfWindowHeight - closest))) {
closest = this;
}
});
var listPointId = listPointIdPrefix+Math.abs(1+positions.indexOf(Math.abs(closest)));
if(!$(listPointId).hasClass(activeSection)){
$(listPointId).addClass(activeSection);
if(listPointId != lastListPoint){
$(lastListPoint).removeClass(activeSection);
};
lastListPoint = listPointId;
};
};