Tips for showcasing the currently active item in a Bootstrap dropdown menu using jQuery

I am trying to highlight the menu item that is selected in a drop-down menu. I attempted the following code, which works if I prevent the default behavior of the link element, but I do not want to do that. So I tried using local storage instead, but it does not work as expected - the page only refreshes and the default "Home" item in the menu remains highlighted.

Menu

<ul class="nav navbar-nav">
    <li class="active"><a href="index.php">Home</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Fire &amp; Water <span class="caret"></span></a>
      <ul class="dropdown-menu" role="menu">
        <li><a href="water-damage-restoration.php">Water Damage</a></li>
        <li><a href="fire-smoke-damage-restoration.php">Fire Damage</a></li>
        <li><a href="storm-flooding-restoration.php">Storm Damage</a></li>
        <li><a href="commercial-restoration-services.php">Commercial Restoration</a></li>
      </ul>
    </li>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Mold <span class="caret"></span></a>
        <ul class="dropdown-menu" role="menu">
            <li><a href="mold-remediation.php">Mold Remediation</a></li>
            <li><a href="black-mold.php">What is Black Mold?</a></li>
            <li><a href="mold-removal.php">Mold "Removal" vs Remediation</a></li>
            <li><a href="commercial-mold-removal.php">Commercial Mold Remediation</a></li>
        </ul>
    </li>
</ul>

This is Working

$(document).ready(function(){
    $(".dropdown-menu li a").click(function(e){
        e.preventDefault();
        var hrefs = $(this).attr('href');
        alert("hrefs : " + hrefs);
        $("li").removeClass('active');
        $('a[href="' + hrefs + '"]').parents('li').addClass('active');
    });
});

This is not working

$(document).ready(function(){
    $(".dropdown-menu li a").click(function(){
        var hrefs = $(this).attr('href');
        alert("hrefs : " + hrefs);
        localStorage.setItem('activeTab', hrefs);
        var activeTab = localStorage.getItem('activeTab');
        $("li").removeClass('active');
        alert("activeTab : " + activeTab);
        $('a[href="' + activeTab + '"]').parents('li').addClass('active');
    });
});

Answer №1

Instead of applying the active class on a click event, it is recommended to apply it on the page load event. Your code should look something like this:

$(document).ready(function(){
    // Set the active class for the current link in the left navigation
    var current_url = window.location;
    $('.dropdown-menu li a').filter(function () {
        return this.href == current_url;
    }).last().parents('li').addClass('active');
});

On each page load, filter out the link of the current page from your navigation bar and then add the active class to its parent element. The code provided above is for demonstration purposes, you will need to adjust it based on your HTML structure.

Give it a try and hopefully it works as expected :)

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

When refreshing the page, the authentication token set in the Vuex store using axios in Nuxt.js/Vue.js gets reset

Here is the code snippet I am using to manage login, logout, user retrieval, and token setting for all axios requests as an auth header. While this code works perfectly during client-side rendering - such as logging in, storing the token in cookies, etc. ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API. After trying various approaches for about 4 days, none seem to be effective. TARGET Require axios REQUEST interceptor t ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

The webpack production build consistently displays the message "This site is running on the development build of React."

I have been attempting to utilize webpack-4 for generating a production build of my React project (not built with Create React App), but I am facing difficulties. The project is written in TypeScript and uses ts-loader, as well as React version 15.6.2. Be ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

Questioning the credibility of a JSON response

Here is a fragment of my code: $.getJSON('../encomendasanexos.php?campo=idencomendas&nome=imagem&id='+id_int, function(registro){ var imghtml = []; imghtml = '<img src="icones/editar.png" onclick ...

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...

Is it possible for a cloud function to safely carry out asynchronous tasks after it has fulfilled its promise?

Is it safe for a cloud function to execute async tasks after returning its promise? Take into consideration the following code pattern: exports.deleteUser = functions.auth.user().onDelete(async (user) => { const uid = user.uid; asyncTask1(uid); ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

Is there a way to remove this annoying line? Or perhaps just reformat it somehow?

I seem to be overlooking a small detail. I have created an html table with Bootstrap5 css, but I am struggling with the formatting. How can I remove the black line or adjust the boldness of the text in the table header? Check out the Table Header Row Bel ...

Leveraging functions in a Node.js module

I am struggling with using a function inside a Node.js module. I have implemented a custom sorting function to sort an array of objects based on the value of a specific property. exports.getResult = function(cards) { cards.sort(sortByField('suit& ...

Changing the source of the Carousel image in HTML when it is the active image

I have a unique setup with two carousels on a single page. My goal is to change the src of the first item in the carousel when the second item is clicked. Here is the code for the second carousel item: <div style="max-width: 20%; max-height: 20%;" cl ...

Dealing with Issues in Projectile Image Display: Solutions for Resolving the Error

I've been attempting to change my projectile from circles to images, but I'm encountering this error File "C:\Users\Habib\Desktop\PYTHONGGAME\py.py", line 353, in <module> bullets.append(projectile(round(player ...

Deduct x days from a Date String in a React Component

How can I subtract a specified number of days from a date that is in string format, like "2021-07-19"? I attempted to convert the string into a date, subtract the days, and then convert it back to a string, but this method did not produce the desired resu ...

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...