Presently, I am focusing on enhancing the navigation bar of my website, but I have encountered an issue with my JavaScript code. I have implemented a scroll-spy feature in my navigation and added JavaScript for smooth scrolling. Additionally, I aim to make the background color of the nav-items(links) change as users scroll to different sections of the website. Although I have created what seems like appropriate code for this functionality, it fails to work - it simply does not respond.
scroll_navbar {
position: fixed;
width: 14%;
height: 100vh;
z-index: 3;
padding: 0;
padding-left: 1%;
}
.nav-item {
background-color: rgba(255,255,255,0.6)!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item :hover {
background-color: rgba(255,255,255,1)!important;
color: rgb(0,0,0);
}
body {
position: relative;
}
.active {
background-color: rgba(255,255,255,1)!important;
}
.nav-link {
color: #000000;
}
.nav-item.scrolled {
background-color: rgba(249,71,108,0.6)!important;
margin: 6px;
transition: 0.7s all;
}
.nav-item .scrolled :hover {
background-color: rgba(249,71,108,1) !important;
color: rgb(0,0,0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container d-flex align-items-center" id="scroll_navbar">
<div class="row">
<div class="col" style="padding: 0;">
<div id="spy">
<ul class="nav flex-column">
<li class="nav-item"><a href="#part1" class="nav-link">home</a></li>
<li class="nav-item"><a href="#part2" class="nav-link">about</a></li>
<li class="nav-item"><a href="#part3" class="nav-link">price</a></li>
<li class="nav-item"><a href="#part4" class="nav-link">contact</a></li>
</ul>
</div>
</div>
</div>
</div>
<script>
$(function () {
$(window).scroll(function () {
var $nav = $('.nav-item');
$nav.toggleClass('scrolled', $(this).scrollTop() >
$nav.height());
});
});
</script>
<script> $('body').scrollspy({ target: '#spy'}) </script>
<script src="smooth-scroll.js"></script>
<script>
var scroll = new SmoothScroll('a[href*="#"]');
</script>
Is there a more effective solution you can suggest to alter the background color of my links (nav-item)?