JSFiddle - React, Tailwind, and code Playground
by RAX7
HTML
<div class="fixed-nav">fixed-nav</div>
<div class="container">
<section class="scrollspy dark">section-1</section>
<section class="scrollspy">section-2</section>
<section class="scrollspy dark">section-3</section>
<section class="scrollspy">section-4</section>
<section class="scrollspy dark">section-5</section>
<section class="scrollspy">section-6</section>
<section class="scrollspy dark">section-7</section>
</div>
CSS
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: sans-serif;
}
.fixed-nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 50px;
padding: 0 20px;
background-color: #222;
color: #eee;
border: 1px dashed purple;
transition: all 500ms;
}
.fixed-nav--light {
background-color: #ccc;
color: #222;
}
.container {
max-width: 500px;
padding: 50px 20px 0;
margin: 0 auto;
}
.scrollspy {
padding: 15px;
height: 66vh;
background-color: #ccc;
color: #222;
}
.dark {
background-color: #222;
color: #ccc;
}
JavaScript
const navigation = document.querySelector('.fixed-nav');
const sections = document.querySelectorAll('.scrollspy');
function onScroll() {
const nRect = navigation.getBoundingClientRect();
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
const sRect = section.getBoundingClientRect();
if (sRect.top < nRect.bottom && sRect.bottom > nRect.bottom) {
const isDark = section.classList.contains('dark');
navigation.classList.toggle('fixed-nav--light', !isDark);
break;
}
}
}
window.addEventListener('scroll', onScroll);
onScroll();