JSFiddle - React, Tailwind, and code Playground
by luka kupunia
HTML
<nav>
<a href="nav-1">nav 1</a>
<a href="nav-2">nav 2</a>
<a href="nav-3">nav 3</a>
<a href="nav-4">nav 4</a>
</nav>
<main>
<section id="nav-1" class="navlink"></section>
<section id="nav-2" class="navlink" style="margin-top: 1px"></section>
<section id="nav-3" class="navlink"></section>
<section id="nav-4" class="navlink"></section>
</main>
CSS
body {
margin: 0;
}
* {
box-sizing: border-box;
}
nav {
position: fixed;
background: #eee;
padding: 10px;
z-index: 2;
}
nav a {
font-size: 20px;
text-decoration: none;
color: black;
margin: 0 10px;
}
nav a.active {
text-decoration: underline;
}
section {
height: 100vh;
opacity: 0.2;
}
section:nth-child(1) {
background: red;
}
section:nth-child(2) {
background: blue;
}
section:nth-child(3) {
background: yellow;
}
section:nth-child(4) {
background: brown;
}
JavaScript
var sections = document.querySelectorAll('.navlink')
var observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
sections.forEach(function(el){
el.classList.remove('active')
})
entry.target.classList.add('active')
}
});
}, { rootMargin: "0px 0px 0px 0px" });
document.querySelectorAll('.navlink').forEach(el => { observer.observe(el) });