Utilize a dynamic approach to add the active class to navigation list items

My files all have a header that includes a navigation bar. I am trying to use jQuery to add the 'active' class to the relevant list items (li).

The method I initially thought of involved setting a variable on each page, assigning an ID equal to that variable for the relevant page, and then using a function to check if they match in order to apply a class to the li element.

However, I believe there must be a simpler way to accomplish this task.

<ul class="nav nav-pills right" id="div">
    <li id="home" class="active">
       <a href="index.php">Home</a>
    </li>
    <li id="search">
       <a href="search.php">Search</a>
    </li>
    <li id="contact">
      <a href="contact.php">Contact</a>
    </li>
</ul>

Answer №1

An efficient solution is to create a separate script for each page:

$('#home').addClass('active'); // apply active class to home page

Another approach is to match the current URL with the links:

var path = window.location.pathname.substring(1);
$('.nav>li>a[href="' + path + '"]').parent().addClass('active');

Answer №2

A more streamlined method:

$(document).ready(function(){
    var currentPath = window.location.pathname;
    var currentPage = currentPath.substring(currentPath.lastIndexOf('/') + 1);
    $('a[href="'+ currentPage +'"]').parent().addClass('active');
});

Answer №3

Upon loading the page, this code will be executed:

$(document).ready(function(){
    $('li').removeClass('active');
    $('li a').each(function() {
       $found = $.contains($(this).prop("href"),location.pathname);
       if ($found) {
           $(this).closest('li').addClass('active');
           break;
        }
    });
});

Alternatively,

You can achieve this using regex:

$(document).ready(function(){
    $('li').removeClass('active');
     var regex = /[a-z]+.php/g; 
     var input = location.pathname; 
        if(regex.test(input)) {
           var matches = input.match(regex);
           $('a[href="'+matches[0]+'"]').closest('li').addClass('active');
        }
});

Ensure that the id name is similar to that of the php file.

View the demonstration here: Demo

Answer №4

Here is a solution to achieve the desired result:

// First, remove the active class from all items (if there are any)
$('.nav>li').removeClass('active');

// Next, add the active class to the current item
$('a[href='+ location.pathname.substring(1) +']').parent().addClass('active');

Answer №5

One potential method involves utilizing JavaScript to locate the current list item by referencing the URL and assigning a corresponding class once the DOM is fully loaded. This can be achieved through manipulating the window.location string in combination with JQuery selectors and addClass() function.

Answer №6

I came across a script that adds an active (current) class to my shared menu, but I need to tweak it so that only the parent link is set, not the closest link. It works perfectly for menu items without submenus, but after clicking on a submenu item, there is no indication on the main menu once the page reloads. Here's the code snippet that requires modification:

(function( $ ) { $.fn.activeNavigation = function(selector) { var pathname = window.location.pathname; var extension_position; var href; var hrefs = []; $(selector).find("a").each(function(){ // Remove href file extension extension_position = $(this).attr("href").lastIndexOf('.'); href = (extension_position >= 0) ? $(this).attr("href").substr(0, extension_position) : $(this).attr("href");

        if (pathname.indexOf(href) > -1) {
            hrefs.push($(this));
        }
    })
    if (hrefs.length) {
        hrefs.sort(function(a,b){
            return b.attr("href").length - a.attr("href").length
        })
      hrefs[0].closest('li').addClass("current")
    }
}; })(jQuery);

Answer №7

If you happen to be searching on Google for a solution, here is what worked for me:

var url = window.location.href; // storing the full URL in a variable
$('a[href="'+ url +'"]').parent().addClass('active'); // finding and adding class 'active' to the parent of the link with the matching URL

This is how the HTML structure looks like:

<ul class="navbar-nav mr-auto">
    <li class="nav-item">
        <a class="nav-link" href="http://example.com/">Home</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="http://example.com/history"> History</a>
    </li>
</ul>

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

What is the best way to implement a gradual decrease in padding as the viewport resizes using JavaScript

My goal is to create a responsive design where the padding-left of my box gradually decreases as the website width changes. I want the decrease in padding to stop once it reaches 0. For instance, if the screen size changes by 1px, then the padding-left sh ...

What is the best way to ensure that any modifications made to an item in a table are appropriately synced

Utilizing xeditable.js, I am able to dynamically update the content of a cell within a table. My goal is to capture these changes and send them via an HTTP request (PUT) to the backend in order to update the database. Below is the table that can be edited ...

Working with color fills in Three.js shapes

Looking for some help with code that generates a yellow circle: let radius = 5, segments = 64, material = new THREE.LineBasicMaterial( { color: 0xF0C400 } ), geometry = new THREE.CircleGeometry( radius, segments ); geometry.vertices.shift ...

`Arranging Widget Boxes in a Vertical Layout`

I am currently displaying each record with two boxes for Afternoon and Night horizontally: https://i.stack.imgur.com/JMKug.png This is the code structure I am using to achieve this layout: <div id="record_box"> <div class="row" style="paddi ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

JavaScript Bingo Game - Create Interactive Cell Selection

Below is the HTML code that I am using to create a Bingo card: ... <th class="orange">B</th> <th class="orange">I</th> <th class="orange">N</th> ...

Using HTML5 to Define the Size of a File Upload Button

The validation error from W3C states: "Attribute size is not permitted for the input element at this location." <input type="file" name="foo" size="40" /> How should the width of a file input be specified in HTML5? ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

Transforming JSON data into a dynamic Tableview

I've been experimenting with this issue for quite some time now, but I can't seem to find a solution. My API returns tasks in JSON format. When I print the data using Ti.API.info(this.responseText), it looks like this: [INFO] [{"created_at":"20 ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Form validation errors were detected

Currently, I am working with a formgroup that contains input fields with validations set up in the following manner: <mat-form-field class="mat-width-98" appearance="outline"> <mat-label>Profession Oc ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Using the `find()` method in a loop of Mongoose iterate

Searching for documents based on conditions stored in an array can be quite useful. Take this example: subscriptions=[ {teacher: 'john', student:'david' ,course:'math'}, {teacher: 'john', student:'david' , ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

What are the steps to establish a Z-axis coordinate system in three.js?

When working with three.js, the Y axis typically represents up and down, while the Z axis represents forward and backward. However, I want to switch this so that the Z axis represents up and down, and the Y axis represents forward and backward. Here is an ...

Angularjs: The Art of Loading Modules

I am facing an issue while trying to load certain modules. controller1.js: angular.module('LPC') .controller('lista_peliculas_controller', ['$scope', function($scope) { $scope.hola="hola peliculas"; }]); And ap ...

Troubleshooting Problem with Web Forms and Bootstrap Form Design

Currently, I am utilizing a simplified version of the Admin LTE Bootstrap Theme in an ASP.NET Web Forms Project. In this project type, only one form tag can be used per page. The form tag must encapsulate both the Top (Nav) and Bottom (Side Bar Left & Mai ...

A skeleton framework lacking a data storage backend

I am currently developing an offline javascript application that must be compatible with IE7, ruling out the use of localStorage. The app does not require any information persistence, as a refresh clears everything. My query is regarding setting up Backbo ...

Do factory and service represent examples of Declarative Programming within AngularJS?

Angular JS involves the declaration of services and factories. Services are created by declaring functions that we do not manually call ourselves. Could this be considered declarative programming, with the framework handling the imperative tasks? What ex ...