Issue with Changing Active Class in Bootstrap Menu

I have been attempting various approaches to change the active class on a Bootstrap navbar (in Bootstrap 4), but I am facing difficulties. Each time I click on a new menu option, it momentarily changes to the active class before reverting back to 'home' being active.

Below is my navbar:

 <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">About</a>
            </li>
             <li class="nav-item">
                <a class="nav-link" href="/blog">Blog</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Contact</a>
            </li>

            <li class="nav-item btn-group">
                <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Deals
                </a>
                <div class="dropdown-menu dropdown-primary" aria-labelledby="navbarDropdownMenuLink">
                    <a class="dropdown-item" href="#">Action</a>
                    <a class="dropdown-item" href="#">Another action</a>
                    <a class="dropdown-item" href="#">Something else here</a>
                </div>
            </li>
        </ul>

This is my javascript code:

 <script>
            $(".navbar-nav li").on("click", function(){
            $(".navbar-nav li").removeClass("active");
            $(this).addClass("active");
            });
        </script>

Answer №1

No need for any custom JavaScript coding. Simply utilize the bootstrap.js file in conjunction with jQuery.

Avoid trying to recreate existing solutions. Take advantage of the tools and resources already available.

Ensure you load the following 3 files in the specified order:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

Your navbar may be missing some elements, refer to the documentation here for more information:

https://getbootstrap.com/docs/4.0/components/navbar/

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

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

How can you use ES6 pure Javascript to set the src attribute of an html collection of images from an array of paths as values for each image?

Currently, I have an array filled with different src values like [path1, path2, path3], and a corresponding HTML collection which has the same number of elements as the array. I am looking for a way to assign each value from the array to set the src attrib ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Update the content of an HTML element without having direct access to the HTML code

I am currently in the process of creating a website using a website builder, and I am interested in customizing the default message that is displayed when a required field in the website form is left empty. The form in question is an integral part of the w ...

A novel RxJS5 operator, resembling `.combineLatest`, yet triggers whenever an individual observable emits

I am searching for a solution to merge multiple Observables into a flattened tuple containing scalar values. This functionality is similar to .combineLatest(), but with the added feature that it should emit a new value tuple even if one of the source obser ...

Express is having trouble retrieving the query parameter from the URL

Working with the express framework and react on the front end application to handle HTTP requests in a node app, I have the following method: app.get('/api/matches', async (req, res) => { console.log(req.originalUrl); // /api/matches/ cons ...

Automatically opening a link upon page load using JavaScript

I am attempting to write a JavaScript code that will automatically click on the link with the ID "bigPicLink" when the page loads, but I am having trouble getting it to work. I am new to JavaScript and would greatly appreciate any assistance. Thank you. ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

Issue arises in Vue.js component array misalignment upon substituting with a smaller array

My journey with Vue.js (version 2.5.16) has just begun, but I've encountered a puzzling issue related to Reactivity: I have two sets of components displayed using v-for, which mostly render correctly - I can interact with them and even add new ones. ...

Classes for defining specific breakpoints in Bootstrap's grid system

Is it possible to create a Bootstrap class that applies specifically to certain breakpoints? I am aware of classes like col-sm-2 col-md-4, but I am looking for something that allows me to set the width of an element. Currently, to set the width to 100%, ...

AngularJS DataGrid export options

Utilizing the angular-datatable plugin, complete with export buttons. You can see an example here: vm.dtOptions = DTOptionsBuilder.fromSource('data.json') .withDOM('frtip') .withPaginationType('full_numbers') // ...

Best practices for transferring data in node.js (unresolved)

Is it possible to pipe a file from an external server through localhost using Node.JS? (Imagine loading localhost as if it were another site like ) Here is the scenario: A PC requests http://localhost:80/highres/switch.html The Node application then ...

Excessive white space on WordPress pages is creating a less than ideal

On my WordPress page, I have set up a row with the main side at span10 and the right sidebar at span2. However, the layout leaves too much blank space, causing users to scroll to the right and see nothing. You can view the specific page here Below is the ...

What is preventing JSFiddle from displaying this object?

I'm currently experimenting with objects in Angular. While using JSFiddle to define some JSON objects in an Angular controller, I've encountered a problem - it's not working and I can't seem to figure out why. Can someone with fresh ey ...

Picture emerges from the lineup

My dilemma involves repositioning an image within a row > col-md-6. To address this, I devised two classes - .pos1 and .pos2 .pos1 { position: relative; } .pos2 { position: absolute; right: 0px; } However, when applying these classes, the ...

Choose the dropdown item depending on the related text

I am currently working on a drop-down menu where each option has a value and associated text. The selected option is then displayed row by row in a table, with an edit button next to each row that allows the user to change the selection. I am trying to imp ...

How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="boxes"> <div class="red" style="width: 300px; height: 300px; color: red"></div> <div class="blue ...

How can I center the carousel on the page?

<div id="imageCarousel" class="carousel slide" data-interval="3000" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#imageCarousel" data-slide-to="0" class="active"></li> ...

How can I place a div using pixel positioning while still allowing it to occupy space as if it were absolutely positioned?

I successfully created an slds path element with multiple steps. I want to display additional subtext information below each current step, but there might not always be subtext for every step. To achieve this, I created an absolute positioned div containi ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...