Steps for Updating Navigation List Link on Page Scroll in Bootstrap 5

I've been working on changing the navigation link color when scrolling in Bootstrap 5. To illustrate the problem, I've created a fiddle which you can check out here:

https://jsfiddle.net/mfen723/8kvf0431/20/

My approach involves using the following function to update the color of the nav links as the user scrolls:

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');
});

After examining the nav links in the dev tools post-scrolling, I noticed that the ul.navbar-nav-scroll class is indeed added to the links but it doesn't affect the color. The CSS for this class is as follows:

ul.navbar-nav-scroll .nav-link {
  color: var(--blue-accent-light) !important;
}

Even with the use of the !important rule to override previous styles, the desired outcome is not achieved. Any assistance in solving this issue would be greatly appreciated.

Answer №1

In order to make the necessary changes, you will need to update the following strings:

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');
        });   

The updated code should look like this:

const navUlScroll = document.querySelector('ul.navbar-nav');

        window.addEventListener('scroll', () => {
            if (window.scrollY >= 26) {
                navUlScroll.classList.add('navbar-nav-scroll');
            } else if (window.scrollY < 56)
                navUlScroll.classList.remove('navbar-nav-scroll');
        });   

You can view a live example of the updated code here.

Answer №2

Your CSS bug was caused by using the wrong class name.

When adding the ul.navbar-nav-scroll class to an anchor element (<a>), remember that ul.navbar-nav-scroll is meant for a <ul> element with class 'navbar-nav-scroll'.

ul.navbar-nav-scroll // --> <ul class='navbar-nav-scroll' ...>

It's important not to specify the element type (ul.) when using classList, as it can create a className like

<a class='ul.navbar-nav-scroll'..>

Check out the fixed fiddle here: https://jsfiddle.net/07jonqf9/

And the corrected code snippets:

const navUlScroll = document.querySelector('a.nav-link');

        window.addEventListener('scroll', () => {
            if (window.scrollY >= 26) {
                navUlScroll.classList.add('navbar-nav-scroll');
            } else if (window.scrollY < 56)
                navUlScroll.classList.remove('navbar-nav-scroll');
        }); 

a.navbar-nav-scroll  {
  color: var(--blue-accent-light) !important;
}

Answer №3

Here are some quick tweaks you can make to your Fiddle for better results.

Check out the Live Fiddle

  • To change all link colors, use querySelectorAll.
  • Refer to CSS Selectors. The CSS selector ul.navbar-nav-scroll selects all ul elements with the class navbar-nav-scroll.
  • The solution includes adding the class navbar-nav-scroll to the 'a' tags. The CSS selector a.navbar-nav-scroll.nav-link applies to items with both class names.

Javascript

const navUlScrolls = document.querySelectorAll('a.nav-link');

window.addEventListener('scroll', () => {

  for (const navUlScroll of navUlScrolls) {
    if (window.scrollY >= 26) {
      navUlScroll.classList.add('navbar-nav-scroll');
    } else if (window.scrollY < 56)
      navUlScroll.classList.remove('navbar-nav-scroll');
  }

});

CSS

a.navbar-nav-scroll.nav-link   {
  color: var(--blue-accent-light);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on how to truncate decimal places dynamically using the toFixed method without rounding

I've been searching for a solution to this particular issue, but it seems that there isn't a similar case on Stack Overflow where the decimal precision needs to be adjustable. Currently, I'm working on a React cryptocurrency project and I wa ...

Nested pages in the NextJS router do not properly highlight the active menu item

I am currently working with NextJS and facing an issue with setting active menu items using the router. While the 'top level' pages behave as expected, any page under a top level page does not get set as active. router.pathname == "/profile& ...

Adding images and textures to a Three.js JSON object file is a simple yet essential process that can greatly enhance

My main objective is to import a 3D model from 3DS/MAX into WebGL using the powerful Three.js library. I've made progress towards this goal through the following steps. Initially tried exporting from MAX plugin exporter straight to Three.js JSON, bu ...

Try to refrain from invoking effect within a component that is being conditionally rendered

I have a particular component that I am working with: const Component = () => { useEffect(() => { console.log('Executing useEffect in the Component') }, []) return <Text>element</Text>; } Whenever I conditionally re ...

Using jQuery to alter the class of div elements in a specific sequence

Currently, I am working on a blog layout using Bootstrap and have encountered an issue. The specific layout requirement is to have the first two divs as col-md-3 (NORMAL), followed by the next 2 divs as col-md-6 (WIDE), then repeating this pattern for the ...

Determine in React whether a function returns a true value, and execute the code for false regardless

I have a hunch that this is related to the concept of asynchronicity. Essentially, I'm trying to validate whether a string (an answer to a question) already exists. If it does, the page should just show a message; otherwise, it should add the new que ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

Customize the inline click event using jQuery

I have a navigation with links that resemble the following: <a id="navform" href="#" tabindex="-1" onclick="mojarra.ab(this,event,'action','@form','content');return false" class=" ...

My goal is to manage components asynchronously in Nuxt.js while also showcasing alert messages

My Desired Outcome I am hoping to implement a notification system that notifies the user based on the response from the server. However, since notifications are handled by a separate component, I need to asynchronously call this component in my code. The ...

Creating nested tabs using vanilla JavaScript, no need for jQuery

I am currently working on implementing tabs using a JavaScript function. The issue I am facing is that when I try to have tabs within one of the tabs, everything disappears every time I click on one of the inner tabs. This happens because the JavaScript fu ...

Utilizing Vue.js for Keyboard Binding

I'm brand new to coding and Vue, and I've hit a roadblock in my project. I'm creating a JavaScript calculator that needs to be usable both with a mouse and keyboard. While I've managed to make it work with the mouse, I just can't ...

Picture enclosed in a div element with blurred borders

I have a question regarding an image that was dynamically changed using JavaScript. The issue I'm facing is that the new image appears to be placed on top of a background image, resulting in a clear square outline around it. I'd like to know if t ...

Utilizing custom validity for asynchronous validation of forms

I am implementing a feature where users can only submit the form if the user does not already exist. To achieve this, I have created a custom rest API to check if the entered user already exists either on input blur or form submission. This approach has be ...

Ways to customize the CSS of a website specifically for mobile browsers

I recently made some tweaks to the dropdown menu design on my website, and now it looks much better on mobile devices with a aqua light green/blue header color and #333 text in the dropdown. However, when I switch back to the desktop version, the entire me ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

Tips for generating arrays using cell data from Google Sheets

I am currently working on extracting information from a Google Sheet to create a list of (4X1) arrays. A B C D E F G H I J Project | Per1 | W1 | Team1 | Per2 | W2 | Team2 | Per3 | W3 | Team3| ———— ...

What is the process for incorporating Material-UI into a JSFiddle project?

I'm having trouble figuring out how to load and use the Material UI script on platforms like JSFiddle or SO's code editor, even though I can add it with NPM. Check out this JSFiddle example <script src="https://unpkg.com/@material-ui/core/um ...

The JQuery Clone function seems to be malfunctioning on Chrome, yet operates smoothly on Firefox

I've been struggling to make my jsfiddle work for some time now. I discovered why it functions in Firefox but not in Chrome or IE. The issue lies with the additional class="name". Removing it, along with my custom validation rules, allows it to work, ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...