JSFiddle - React, Tailwind, and code Playground
by Brett
HTML
<nav>
<ul>
<li id="whatbutton"><a href="#whatissm">What We Are</a></li>
<li id="whybutton"><a href="#whyusesm">Why Us</a></li>
<li id="offerbutton"><a href="#whatdoessmoffer">What We Offer</a></li>
<li id="contactbutton"><a href="#contactus">Contact Us</a></li>
</ul>
</nav>
<div>
<h1 id="whatissm" name="whatissm"><span>what we are</span></h1>
<h1 id="whyusesm" name="whyusesm"><span>why us</span></h1>
<h1 id="whatdoessmoffer" name="whatdoessmoffer"><span>what we offer</span></h1>
<h1 id="contactus" name="contactus"><span>Contact Us</span></h1>
</div>
CSS
nav {
position: fixed;
right: 20px;
top: 20px;
}
div {
height: 2000px;
}
div > h1 {
height: 200px;
}
.active {
color: red;
}
JavaScript
const anchors = $('body').find('h1');
$(window).scroll(function(){
var scrollTop = $(document).scrollTop();
// highlight the last scrolled-to: set everything inactive first
for (var i = 0; i < anchors.length; i++){
$('nav ul li a[href="#' + $(anchors[i]).attr('id') + '"]').removeClass('active');
}
// then iterate backwards, on the first match highlight it and break
for (var i = anchors.length-1; i >= 0; i--){
if (scrollTop > $(anchors[i]).offset().top - 75) {
$('nav ul li a[href="#' + $(anchors[i]).attr('id') + '"]').addClass('active');
break;
}
}
});