I am trying to change the nav link color on page scroll in Bootstrap 5. I have created a fiddle to show the problem, which is linked to below:
https://jsfiddle.net/mfen723/8kvf0431/20/
I am using the following function to try to change the color of the nav links after scrolling:
const navUlScroll = document.querySelector('a.nav-link');
window.addEventListener('scroll', () => {
if (window.scrollY >= 26) {
navUlScroll.classList.add('ul.navbar-nav-scroll');
} else if (window.scrollY < 56)
navUlScroll.classList.remove('ul.navbar-nav-scroll');
});
When I inspect the nav links (after scrolling) with dev tools I can see that the ul.navbar-nav-scroll
class is added to the nav links but this has no effect on the color. The class consists of the following CSS:
ul.navbar-nav-scroll .nav-link {
color: var(--blue-accent-light) !important;
}
I have used the !important rule to override any previous styling but it’s still not working. Any help with this issue would be much appreciated.
3
Answers
You need to replace these strings:
on this:
Here is a live example: https://jsfiddle.net/wpexpert/jwsp3noy/4/
These small changes to your Fiddle should get your result.
Live Fiddle
ul.navbar-nav-scroll
in the CSS file selects allul
with the classnavbar-nav-scroll
.navbar-nav-scroll
to the ‘a’ tags and the CSS selector is fora.navbar-nav-scroll.nav-link
so applies to items that have both class names.JS
CSS
The wrong class name and your CSS caused this bug.
In JS you add
ul.navbar-nav-scroll
class to anchor (<a>
) element but actuallyul.navbar-nav-scroll
means that:You shouldn’t specify element type (ul.) when adding classList. Because it create a className like this
<a class='ul.navbar-nav-scroll'..>
Your fixed fiddle is here: https://jsfiddle.net/07jonqf9/
And fixed snippets here: