I want to add a active class when scroll my page. when href and top navbar id is same then add a active class for highlight this nav
$(document).ready(function(){
$(window).scroll(function() {
$.each(items, function(key, value){
var item = $(value);
if(window.scrollTop() >= item.offset().top){
$('.menu a.active').removeClass('active');
var id = item.attr('id');
console.log(id);
$.each(navItems, function(key, value){
var navItem = $(value);
if(navItem.attr('href') == '#'+id) navItem.addClass('active');
});
}
});
});
});
ul.menu{
position: fixed;
top: 0;
}
ul.menu li{
display:inline-block;
list-style: none;
margin-right: 10px;
}
.menu li a{
text-decoration: none;
}
a.active{
color: red;
}
#home{
margin-top: 80px;
}
#home, #profile, #aboutus, #contactus{
min-height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="menu">
<li><a href="#home" class="active">Home</a></li>
<li><a href="#profile" class=" ">Profile</a></li>
<li><a href="#aboutus" class="">About Us</a></li>
<li><a href="#contactus" class="">Contact Us</a></li>
</ul>
<div id="home">
<h3>this is home</h3>
</div>
<div id="profile">
<h3>this is profile</h3>
</div>
<div id="aboutus">
<h3>this is aboutus</h3>
</div>
<div id="contactus">
<h3>this is contactus</h3>
</div>
Here is above my code but its not working show scrollTop is not a function and class is not added when i scroll the page..