Home > Web Front-end > CSS Tutorial > How Can I Toggle CSS Classes on Click Using jQuery to Manage Active Menu Items?

How Can I Toggle CSS Classes on Click Using jQuery to Manage Active Menu Items?

Mary-Kate Olsen
Release: 2024-11-25 05:43:17
Original
335 people have browsed it

How Can I Toggle CSS Classes on Click Using jQuery to Manage Active Menu Items?

Toggling CSS Classes on Click with jQuery

In order to dynamically add and remove CSS classes on click events using jQuery, let's explore the following issue.

The Problem: A menu consists of list items that require a specific class to become active. Upon clicking an item, the class should be added only to that item while removing it from all others. Initially, the "about-link" should have the "current" class by default.

The Solution:

To resolve this issue, we can utilize the following jQuery code:

$('#menu li a').on('click', function(){
    $('#menu li a.current').removeClass('current');
    $(this).addClass('current');
});
Copy after login

In this code:

By following this approach, the "about-link" will initially have the "current" class assigned to it using $('#about-link').addClass('current');. When any other item within the menu is clicked, the "current" class is removed from the previously active item and added to the clicked item, ensuring only one item remains active at all times.

The above is the detailed content of How Can I Toggle CSS Classes on Click Using jQuery to Manage Active Menu Items?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template