Home >Web Front-end >CSS Tutorial >How to Dynamically Add an 'Active' Class to Navigation Links Based on the Current URL?

How to Dynamically Add an 'Active' Class to Navigation Links Based on the Current URL?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-10 16:12:11969browse

How to Dynamically Add an

Add Active Navigation Class to Reflect Current URL

Navigating a website often requires a visible indication of the current page, which can be achieved by adding an "active" class to the corresponding menu item. This article demonstrates how to implement this functionality using JavaScript.

Consider the example navigation menu below, where the "Manage" link should appear as "active" on the "manageIS.aspx" page:

<ul>

The following JavaScript snippet will accomplish the desired effect:

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

This code assigns the current page's pathname to the "current" variable. It then iterates over all the menu links and checks if their "href" attribute matches the current path. If a match is found, the "active" class is added to that link.

Unlike the original JavaScript provided in the question, this approach does not rely on click events and is executed on page load. Therefore, the "active" class persists throughout the page's lifespan, providing a clear indication of the current page at all times.

The above is the detailed content of How to Dynamically Add an 'Active' Class to Navigation Links Based on the Current URL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn