JSFiddle - React, Tailwind, and code Playground
by henryDev
HTML
<section id="main">
<div class="target" id="1">TARGET 1</div>
<div>item 1</div>
<div>item 1<div>
<div>item 1<div>
<div class="target" id="2">TARGET 2</div>
<div>item 2</div>
<div>item 2<div>
<div>item 2<div>
<div class="target" id="3">TARGET 3</div>
<div>item 3</div>
<div>item 3<div>
<div>item 3<div>
<div class="target" id="4">TARGET 4</div>
<div>item 4</div>
<div>item 4<div>
<div>item 4<div>
</section>
<aside id="nav">
<nav>
<a href="#1" class="active">Punkt 1</a>
<a href="#2">Punkt 2</a>
<a href="#3">Punkt 3</a>
<a href="#4">Punkt 4</a>
</nav>
</aside>
CSS
* {
margin: 0;
padding: 0;
}
#main {
width: 75%;
float: right;
}
#main div.target {
background: #ccc;
height: 400px;
}
#main div.target:nth-child(even) {
background: #eee;
}
#nav {
width: 25%;
position: relative;
}
#nav nav {
position: fixed;
width: 25%;
}
#nav a {
border-bottom: 1px solid #666;
color: #333;
display: block;
padding: 10px;
text-align: center;
text-decoration: none;
}
#nav a:hover, #nav a.active {
background: #666;
color: #fff;
}
JavaScript
window.addEventListener('scroll', function() {
document.querySelectorAll('.target').forEach(function(item, index){
if($(window).scrollTop() >= $(this).offset().top) {
var id = $(this).attr('id');
document.querySelector('#nav nav a').classList.remove('active');
document.querySelector('#nav nav a[href=#'+ id +']').classList.add('active');
}
});
});