Home >Web Front-end >CSS Tutorial >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'); });
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!