I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar remains transparent instead of changing color as intended when the page is scrolled.
Here is my code for the navbar:
<nav class="navbar fixed-top navbar-expand-lg navbar-dark p-md-3">
<div class="container-fluid">
<a href="#" class="navbar-brand">WorkonPro</a>
<button
type="button"
class="navbar-toggler"
data-bs-target="#navbarNav"
data-bs-toggle="collapse"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle Navbar"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<div class="mx-auto"></div>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active item-space" href="#" aria-current="page"
>Home</a
>
</li>
<li class="nav-item">
<a class="nav-link item-space" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link item-space" href="#"> Healthcare </a>
</li>
<li class="nav-item">
<a class="nav-link item-space" href="#">Tech</a>
</li>
<li class="nav-item">
<a
href="#"
class="nav-link btn btn-sm item-space grey-button"
style="color: #fff"
role="button"
>Login
</a>
</li>
<li class="nav-item">
<a
href="#"
class="nav-link btn btn-sm item-space green-button"
style="color: #fff"
role="button"
><strong>Create account</strong>
</a>
</li>
</ul>
</div>
</div>
</nav>
Below is the JavaScript code I wrote in an attempt to achieve the desired effect (please note that it corresponds to the body of my HTML page):
<script src="../../../../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script>
var nav = document.querySelector('nav');
window.addEventListener('scroll', function() {
if (window.pageYOffset > 100) {
nav.classList.add('bg-dark', 'shadow');
} else {
nav.classList.remove('bg-dark', 'shadow');
}
});
</script>
Additionally, here is the CSS styling related to the navbar:
.bg-dark {
background-color: #101011 !important;
}
.navbar-dark .navbar-brand {
padding: 20px 0 10px 10px;
color: #fff;
}
.navbar-nav .nav-link {
color: #101011;
}
.navbar-dark .navbar-nav .nav-link {
color: rgba(255, 255, 255, 1);
}
.navbar-dark .navbar-brand {
margin: 0;
width: 50%;
float: left;
display: inherit;
}
.navbar-brand {
color: #101011;
padding: 20px 0 10px 10px;
}
body .navbar {
padding: 6px 0 !important;
}
body .navbar-brand {
background: none;
}
If anyone could point out what I may be missing or doing wrong and provide a solution, I would greatly appreciate it.
Thank you in advance.