Adding an active class to a navigation bar: A step-by-step guide

I've been struggling to assign an "active" class to the navbar selection, but I haven't been able to get it right. I attempted using jQuery to add the class based on an example, but I'm facing difficulties in implementing it successfully. When I click on a link button like Home, the active class should be added. However, despite no console errors being found, the active class simply won't attach to the navbar links.

Here's what I have tried:

My Navbar HTML:

<nav class="navbar navbar-expand-md navbar-light bg-light sticky">
        <a href="#" class="navbar-brand">
            <img src="Assets/Images/spicy-food.svg" height="28" alt="SpiceFoods">
        </a>
        <h2 class="Nav-brand">Spice Foods</h2>
        <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarCollapse">
            <div class="navbar-nav ml-auto">
                <a href="#" data-value="carouselIndicator" class="nav-item nav-link btn-ripple">Home</a>
                <a href="#" data-value="About" class="nav-item nav-link btn-ripple">About</a>
                <a href="#" data-value="Products" class="nav-item nav-link btn-ripple">Our Spices</a>
                <a href="#" data-value="Contact" class="nav-item nav-link btn-ripple">Contact Us</a>
            </div>
        </div>
    </nav>

CSS for Active Class:

.navbar-nav div>a.active {
    background-color: rgba(0, 0, 0, 0.22);
    font-weight: 600;
}

My jQuery Code:

$('.navbar-nav a').on('click', function () {
         console.log("Click");
         $('.navbar-nav').find('a.active').removeClass('active');
         $(this).addClass('active');
     });

If you know how to solve this issue, your help would be greatly appreciated!

Answer №1

Check out the comments below to see the modifications that have been made:

$('.navbar-nav a').on('click', function() {
  $('.navbar-nav').find('a.active').removeClass('active');
  // The previous code $(this).parent('a').addClass('active') was incorrect - there is no parent "a" element... you actually want to add the active class to the clicked element...
  $(this).addClass('active');
});
/* Previously it was .navbar-nav div > a.active ... but there is no div between the navbar and anchor tag.... */
.navbar-nav .active {
  background-color: rgba(0, 0, 0, 0.22);
  font-weight: 600;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav class="navbar navbar-expand-md navbar-light bg-light sticky">
  <a href="#" class="navbar-brand">
    <img src="Assets/Images/spicy-food.svg" height="28" alt="SpiceFoods">
  </a>
  <h2 class="Nav-brand">Spice Foods</h2>
  <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse">
            <span class="navbar-toggler-icon"></span>
        </button>
  <div class="collapse navbar-collapse" id="navbarCollapse">
    <div class="navbar-nav ml-auto">
      <a href="#" data-value="carouselIndicator" class="nav-item nav-link btn-ripple">Home</a>
      <a href="#" data-value="About" class="nav-item nav-link btn-ripple">About</a>
      <a href="#" data-value="Products" class="nav-item nav-link btn-ripple">Our Spices</a>
      <a href="#" data-value="Contact" class="nav-item nav-link btn-ripple">Contact Us</a>
    </div>
  </div>
</nav>

Answer №2

Only one line needs to be modified.

Substitute the following line

$(this).parent('a').addClass('active');

to

$(this).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

Use jQuery to rearrange the order of elements on a webpage by moving a paragraph after a specific

I'm currently experimenting with Codeacademy and I was given a task to move a new paragraph after a div. Here's what I did: $('#one').after('<p>this is jquery</p>'); Now I want to move the new paragraph after ano ...

Searching and filtering arrays in Javascript

Creating a new array based on keyword is what I am aiming for. If my search key word is "align-center" the result should be ["align-center"] "align" the result should be ["align-left", "align-center", "align-right"] "right" the result should be ["alig ...

Is there a way to adjust the height of a turnjs page?

I am currently utilizing the Turn.js flip library and I need to adjust the height of the turnjs page. The current setup calculates the height of the page based on the client's height, but now I want to change it to a specific value like 700px. How can ...

Ways to insert additional panels prior to and after a selected panel

A button is provided in the report designer detail band that, when clicked, should add new panels immediately before and after the detail panel. $parentpanel = $this.parents(".designer-panel:first"); This code snippet is used to locate the parent panel u ...

Is it possible to organize words with HTML elements utilizing JavaScript?

Code is not properly sorting the elements var element='<p><strike>Mango</strike></p>/n<p><em>Orange</em></p>/n<h1>Apple</h1>/n<p><strong>banana</strong></p>/n<p& ...

How can I isolate the CSS of my Vue application from the rest of the website?

I am currently working on developing a unique "plugin" that will feature a user interface to be integrated into various vendor websites. This particular plugin is designed to be CMS agnostic, and due to SEO concerns, I am unable to utilize an iframe. My go ...

Implement the stylesheet to accommodate different screen sizes while still maintaining the integrity of the standard screen

I've been searching through various discussions and questions, but I have not found the exact solution to my issue. The website I created fits within a 960px block for optimal viewing on iPads, but now I need a stylesheet to be applied when the scree ...

The JavaScript function is not functioning properly, whereas another function is working as intended

I have created a HTML form with 2 buttons and a table. Each row in the table consists of a checkbox and 2 text fields. The buttons allow users to add and remove rows from the table. The remove button only applies to rows where their checkbox is checked. T ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Hide error label on field focus using the jQuery validation plugin

I want error labels to be displayed when the user clicks Submit, but I also want them to disappear when the user focuses on a field, even if there is still an error present. The error messages should only reappear when the user clicks submit again. Is the ...

Struggling with CSS Div visibility issue in Laravel 5

My current issue involves using CSS to hide comments within a hidden div, and displaying them when the user clicks "load more." However, if there are multiple statuses, all comments load together when the button is clicked. I'm struggling to identify ...

Using jQuery to slide elements across the page

I've been attempting to incorporate a sliding effect into my website, but I'm running into an issue where the sliding only occurs on the first click and I can't figure out why. Here is the code snippet I've been using: Html : $("#go ...

Is it possible to remove the download button in ViewerJS?

Can the download button on a PDF in ViewerJS be disabled using JQuery without changing the original code provided? I want to achieve this without altering any of the viewerjs files and instead do it in a separate file. ...

Using Cascading Style Sheets (CSS) to make posts appear above an image in a scrolling format

Can anyone guide me on how to show the text above an image contained within a scroll bar, similar to the picture below? Despite trying position property and searching online, I haven't found a solution yet. Your help would be greatly appreciated. ...

Is Chrome not correctly using 100% viewport width (vw)?

I've been attempting to recreate the functionality of this codepen, and I've encountered an issue with the vw declaration in Chrome. Despite setting GalleryGrid to 100vw, it doesn't display correctly in Chrome, while Firefox and Safari work ...

Achieving the grid-column property as you navigate deeper into the tree

Currently, I am in the process of integrating a CSS design that utilizes grid and grid-column into my Angular application. The design itself is quite effective, structured similar to this: .grid { display: grid; grid-template-columns: repeat(3, 1 ...

How can I convert the hover action into a click action?

Greetings everyone! I have created two divs and want to display something only when the h3 is clicked, not hovered over. How can I achieve this? I tried changing hover to click but it didn't work as expected. Apologies for any confusion in my explanat ...

Generating dynamic DOM elements using AngularJS can cause issues with the proper functionality of the Jquery .tab() method

My goal is to dynamically generate a list of elements - the first loop is dedicated to listing tabs for the menu, while the second loop involves the div with the tab contents. When I write it statically, everything works perfectly. However, the dynamic app ...

Tips for positioning two divs in the center of a webpage, both horizontally and vertically, while also including a header and

Currently, I am in the process of creating a new web page with Bootstrap 4. This page consists of four main elements - a header, a footer, and two content boxes contained within divs. While I have successfully utilized default bootstrap classes to ensure t ...

Can I send an AJAX request from an .ascx page? Below is my code for your review

I am working on an .ascx page and facing an issue with calling the .autocomplete function inside it along with an ajax call. Any assistance would be appreciated. $("#txtUsers").autocomplete({ //source: availableTags source: function (request, resp ...