JSFiddle - React, Tailwind, and code Playground
HTML
<div class="current_div" id="section-name">Section Name</div>
<div class="red" data-section="Section Red"></div>
<div class="blue" data-section="Section Blue"></div>
<div class="yellow" data-section="Section Yellow"></div>
<div class="green" data-section="Section Green"></div>
CSS
.current_div {
position: fixed;
top: 0;
width: 100%;
z-index: 100;
}
.colors {
position: relative;
}
.red {
background-color: red;
height: 300px;
}
.blue {
background-color: blue;
height: 300px;
}
.yellow {
background-color: yellow;
height: 300px;
}
.green {
background-color: green;
height: 300px;
}
JavaScript
var elements = document.querySelectorAll("[data-section]"),
sectionName = document.getElementById("section-name");
function onScroll() {
var section = "";
for (var len = elements.length, i = len - 1; i >= 0; i--) {
if (document.body.scrollTop > elements[i].offsetTop) {
section = elements[i].getAttribute("data-section");
break;
}
}
sectionName.innerText = section;
}
document.addEventListener("scroll", onScroll);
onScroll();