How to implement scroll spy in Bootstrap 4 to highlight parent li elements?

I have a bootstrap4 menu set up like this:

<ul class="navbar-nav ml-auto">
<li class="nav-item"><a class="nav-link" href="#introduction">INTRODUCTION <span class="sr-only">(current)</span></a></li>
</ul>

The default scroll spy automatically adds the 'active' class to the nav-link (a) element, but I need it to be added to the nav-item (li) instead. Is there a way to achieve this?

You can see an example of the issue here: Example

When I click on the link, everything works fine, but on scroll, the 'active' class is added to the link instead of the list item.

Answer №1

By default, the .active class is applied only to anchor tags.

To achieve your desired result, you can use the following code snippet:

$('[data-spy="scroll"]').on('activate.bs.scrollspy', function () {
  $(".navbar-nav .active").removeClass("active").parent().addClass("active");
})

Make sure to add the attribute data-spy="scroll"

to the <div class="container"> element, which is the parent of the section with id="introduction"

For example:

<div class="container" data-spy="scroll">

Answer №2

I came across a solution. All I needed to do was add a new event called "cssClassChanged" - and it worked!

(function(){
    // Your base, I'm in it!
    var originalAddClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        // Execute the original method.
        var result = originalAddClassMethod.apply( this, arguments );

        // trigger a custom event
        jQuery(this).trigger('cssClassChanged');

        // return the original result
        return result;
    }
})();

And then

$(".nav-link").bind('cssClassChanged' , function(e) {
        $(".nav-item").each( function() {
            if( $(this).hasClass("active") == true ) {
                $(this).removeClass("active");
            }
        });

        $(this).removeClass("active").parent().addClass("active");
    });

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

Sloped Divider on the Upper Edge of the Page

I'm currently in the process of developing a new website, and I'm looking to create a unique design for the main navigation bar on the homepage. Here is the ideal layout that I have in mind: https://i.stack.imgur.com/pc8z4.png While I understan ...

Determining the Width of a DIV Dynamically with CSS or LESS Depending on the Number of Siblings

One of my challenges involves a parent DIV with a width set to 100%. Dynamically, this parent DIV is filled with numerous children DIVs. I am trying to calculate and assign their widths using only the calc method in CSS or LESS. This is because the flex ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Guiding users who have disabled JavaScript through redirection

When faced with the following markup, users whose browser has JavaScript disabled will be redirected to an alternative page. This alternate page may attempt to mimic the site's functionality without JavaScript or simply display a warning message infor ...

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Exploring ways to track file upload progress with the Fetch API in ReactJS or NextJS

Currently, I am utilizing Nextjs for constructing a full-stack application. Specifically, I am focusing on the admin CMS part and attempting to implement file uploads such as images. Referring to this modified version of the code from this post. The upload ...

Choose the tab labeled "2" within a segment of the webpage

index.html#section takes you to a specific section of a webpage. However, I am interested in picking the second tab within a section of the page. I'm uncertain if this can be achieved without relying on JavaScript, but employing the Tab Content Script ...

Display a single item using Jquery when clicking on an element with the same class

I'm relatively new to JQuery/Javascript scripting and I'm having some difficulty. How can I display one item with the same class without affecting the other items? Here is my code: $(function() { $('.embedContainer > .myPosterImage& ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...

What steps should I take to ensure that the array yields the correct output?

Why is my code not creating an array of [0, 1, 2] when I pass the number 3 as a parameter? const array = [0]; const increment = (num) => { if (num > 0) { increment(num - 1); array.push(num); } return; }; console.log(array); incremen ...

What is the best way to transfer an image between Angular components and then showcase it?

I've developed a feature using an observable and I'm attempting to transfer a dataURL from one component to another in order to display it as an image. Here is the HTML code for the component where I want to send data from: <canvas id="p ...

After clicking, the radio button in Bootstrap 4 shifts to the left

I encountered an issue where the radio button I added to a table using Bootstrap 4 moves slightly to the left whenever I click on it. To better illustrate the problem, I have included a GIF below: https://i.sstatic.net/4aj8f.gif Below is the code for one ...

Expand the size of the image displayed on the modal screen

Having trouble with a modal screen on Bootstrap that is not displaying the full image size. Even after adjusting the modal sizes in the CSS, I'm still unable to get it right. <div class="modal fade bd-example-modal-lg show" id="ftl1Modal" role="d ...

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

Automating the process of running npm start on page load: A guide

Recently, I've been delving into learning npm in order to incorporate it into a website. I'm curious about how exactly it is used within a website - do you typically need to execute the command "npm start"? How does this integration work for a li ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...