Currently, I am attempting to create a feature where links are highlighted when the user scrolls over the corresponding section on the page. However, there seems to be an issue with the functionality as Link 2 is highlighting instead of Link 1 as intended.
<nav>
<ul>
<li><a href="" id="link_1">Link 1</a></li>
<li><a href="" id="link_2">Link 2</a></li>
<li><a href="" id="link_3">Link 3</a></li>
</ul>
<p></p>
</nav>
<div id="sec_one" class="sections">
</div>
<div id="sec_two" class="sections">
</div>
<div id="sec_three" class="sections">
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
*{
margin: 0;
padding: 0;
}
nav{
width: 100%;
background-color: black;
position: fixed;
top: 0;
}
nav ul{
width: 50%;
margin: 0 auto;
list-style-type: none;
text-align: center;
}
nav ul li{
display: inline;
width: 100%;
}
nav ul li a{
font-size: 40px;
color: white;
text-decoration: none;
}
.sections{
width: 100%;
height: 2000px;
}
#sec_one{
background-color: blue;
}
#sec_two{
background-color: red;
}
#sec_three{
background-color: yellow;
}
.active{
background-color: #666666;
}
p{
color: white;
}
$(window).scroll(function(){
var scrollPos = $(window).scrollTop();
var page1Top = $("#sec_one").scrollTop();
var page1Bot = $("#sec_one").outerHeight();
var page2Top = $("#sec_two").scrollTop();
var page2Bot = $("#sec_two").outerHeight();
var page3Top = $("#sec_three").scrollTop();
var page3Bot = $("#sec_three").outerHeight();
if(scrollPos >= page1Top && scrollPos < page1Bot){
$("#link_1").addClass("active");
$("#link_2").removeClass("active");
$("#link_3").removeClass("active");
}else {
$("#link_1").removeClass("active");
}
if(scrollPos >= page2Top && scrollPos < page2Bot){
$("#link_2").addClass("active");
$("#link_1").removeClass("active");
$("#link_3").removeClass("active");
}else {
$("#link_2").removeClass("active");
}
});