This content originally appeared on DEV Community and was authored by Ifeanyi Chima
Today, I want to show you how I darken the navbar when a user scrolls on the website.
THE SECRET
I am using an event listener scroll
which I attached to the navbar to listen for when the user scrolls beyond a certain screen size. This will allow the text on the navbar to be readable.
Using JavaScript, we add two classes to the navbar
bg-dark
: this will give the navbar a dark background. I believe this is an in-built bootstrap class.slow
: this will add animation to make the navbar slowly darken.
HTML
<!--NavBar-->
<nav class="navbar navbar-dark py-3 navbar-expand-lg fixed-top">
<div class="container">
<a href="#" class="navbar-brand">
<img src="./img/halo-logo.jpg" class="img-fluid logo" alt="">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navmenu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navmenu">
<ul class="navbar-nav me-auto">
<li class="nav-item">
<a href="#home" class="nav-link active">GAMES</a>
</li>
<li class="nav-item">
<a href="#news" class="nav-link">NEWS</a>
</li>
<li class="nav-item">
<a href="#about" class="nav-link">ESPORTS</a>
</li>
<li class="nav-item">
<a href="#occupation" class="nav-link">COMMUNITY</a>
</li>
<li class="nav-item">
<a href="#occupation" class="nav-link linkarrow">SUPPORT<i class="ri-arrow-right-up-line"></i></a>
</li>
<li class="nav-item">
<a href="#occupation" class="nav-link linkarrow">GEAR<i class="ri-arrow-right-up-line"></i></a>
</li>
</ul>
<a href="#footer" class="btn btn-brand">GET HALO</a>
</div>
</div>
</nav>
CSS
.slow{
@include transition-ease;
}
@mixin transition-ease{
transition: all 1.4s ease;
}
JavaScript
const nav = document.querySelector("nav");
window.addEventListener("scroll", () => {
if (window.scrollY > 100) {
nav.classList.add("bg-dark", "slow")
} else {
nav.classList.remove("bg-dark", "slow")
}
})
Explaination
we capture the navbar using DOM manipulation.
we add an event listener to the browser window to listen for when a user scrolls beyond 100 vh.
we add the classes “bg-dark” and “slow” to the navbar.
Thank You, Please Follow me.
This content originally appeared on DEV Community and was authored by Ifeanyi Chima