Switching Bootstrap Navbar Active State with JavaScript

I have encountered an issue with using the "active" class on my navbar navigation items in Bootstrap 4. When I click on the links, the active state does not switch as intended. I have tried incorporating JavaScript solutions from similar questions but have been unsuccessful. It's important to note that these links are all on the same page and I want the user to easily identify which section they are currently viewing.

Below is my current JavaScript code:

$(".nav .nav-link").on("click", function(){
    $(".nav").find(".active").removeClass("active");
    $(this).addClass("active");
});

Here is a snippet of my HTML code for the navbar:

<header>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
      <img class="logo" src="images/logo.png" width="55px" align="left">
      <a class="navbar-brand" href="index.html">ROWAN AEΠ</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarCollapse">
      <!--Div for Alignment Purposes Below -->
      <div class="navig-align">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            <a class="nav-link active" href="#HOME">HOME</a>
          </li>
            <li class="nav-item">
              <a class="nav-link" href="#ABOUT">ABOUT</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">BOARD</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">RECRUITMENT</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">FAQ</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">CONTACT</a>
            </li>
            <li class="nav-item">

              <a id="donatebutton" class="nav-link" href="http://www.example.org" target="_blank">DONATE
              <img class="donateimg" src="images/externallink.png" alt=""></a>
            </li>

          </ul>
        </div>
      </div>
    </nav>

  </header>

If anyone can provide insight into how to adjust my script based on the HTML structure provided, I would greatly appreciate it.

Answer №1

It appears that there is no ancestor in the nav list with the class "nav". Additionally, the 'active' class should be applied to the nav-link li elements, not the 'a' tags within them.

You can directly target the active item to remove the active class, whether it's the li or the a tag.

If you prefer to keep the active class on the 'a' tag, simply adjust the click handler like so:

$(".nav-link").on("click", function(){
   $(".nav-link.active").removeClass("active");
   $(this).addClass("active");
});

If you want the active class on the li element instead:

if you want to keep the active class on the a - then just change the click handler

$(".nav-item").on("click", function(){
   $(".nav-item.active).removeClass("active");
   $(this).addClass("active");
});

Answer №2

The jQuery selector you are using does not match any elements with the class .nav.

Consider updating your jQuery code to the following:

$(".nav-link").on("click", function(){
    $(".nav-link.active").removeClass("active");
    $(this).addClass("active");
});

To see an example, visit this link: https://jsfiddle.net/Db2x8h7s/

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

The mouse pointer adjusts according to the event

I am working on an ajax request and I have implemented a feature where the cursor changes appearance. document.body.style.cursor = "wait"; This immediately shows the cursor as a spinning circle when the request starts. At the end of the request, I ch ...

Merging Text within the Yii Framework

Can someone explain the process of combining strings in this code, specifically for first_name and last_name? Thank you in advance for your assistance. <?php /* @var $this AuthassignmentController */ /* @var $data Authassignment */ $datamodel = (Memb ...

Having difficulty displaying a partial view within a view while making an AJAX call

Trying to figure out what's missing in my code. I have a view with some radio buttons and I want to display a different partial view when a radio button is selected. Here's the snippet of my code: Controller public ActionResult Method(string va ...

Extracting raw data from the dojo.xhrGet request

When working with a JSP and servlet, I encountered an issue. In the JSP, I make an ajax call to the servlet which in turn calls a REST API to fetch JSON data. Using json.serialize(true);, I format the JSON data in the servlet before sending it to the front ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

Interacting with the Dropdown feature on the page causes the body of the page to shift

I am encountering an issue with 2 dropdowns in Datatables used to filter content. The problem arises when a dropdown is positioned on the right side of the page, causing a shift to the left by approximately 10px. Conversely, if the dropdown is placed on th ...

Close the Bootstrap modal upon clicking the "Ok" button in SweetAlert2

I need help with closing my Modal Bootstrap after clicking the Ok button in SweetAlert. I've attempted various methods, but none of them have worked so far. I'm not sure if I'm implementing it correctly, but I've utilized JQuery for thi ...

Problems with the bottom section

Is there a way to make the middle section extend downwards when the window is resized, keeping the footer at the bottom without overlapping with the content? If anyone has suggestions on how to achieve this, please share! I'm hoping there's a b ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

Display the title tag when hovering over an image

Hey there! I'm looking to display the title tag of an image directly inside the image itself. Here's an example to illustrate what I mean: http://jsfiddle.net/51csqs0b/ .image { position:relative; width:200px; height:200px; } .ima ...

What is the best way to split two divs in this manner?

Is there a way to split two divs like this in such a manner using TailwindCSS? Alternatively, what would be the CSS code for dividing these two divs? I am struggling with this concept and cannot wrap my head around how it can possibly be achieved. ...

Dynamic banner featuring animated text, automatically resizing divs based on width while maintaining body width

Currently, I am working on creating a banner with moving text. While I have managed to come up with a solution for implementing this effect, there are two significant issues that I am facing. The width values in pixels need to be manually adjusted based ...

What is the functionality of the icon `<i>` in Twitter Bootstrap?

After adding an icon to a webpage, I noticed that it replaced the old, semi-deprecated <i> tag and instead used a customized image tag. It almost seems like <i ...> is just a simpler version of <img ...>. I'm curious about how this ...

AngularJS: Refresh array following the addition of a new item

After saving an object, I am looking to update an array by replacing the conventional push method with a custom function. However, my attempts have not been successful so far. Are there any suggestions on how to rectify this issue? app.controller("produ ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

What is the best way to hide the jQuery modal I created?

Hello everyone! Currently, I am working on coding a simple JS modal that can be opened and closed smoothly. The issue I am facing is related to adding a click function to (.black-overlay) in order to fade out everything and close the modal. <div class ...

unable to effectively test promises with stubs using nodejs mocha

Currently, I am facing a couple of challenges when attempting to perform unit testing on promises using Mocha. 1) The main issue I encounter is an Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Prom ...

How can I use jQuery to pinpoint where my focus currently lies and debug any issues?

Triggering focus() on an element is a simple task, but after encountering debugging problems, I've come to realize that finding out where my focus has shifted can be quite challenging. The issue arises when I'm creating a modal window using jq.UI ...