Home > Web Front-end > CSS Tutorial > How to Use jQuery to Add and Remove CSS Classes on Click?

How to Use jQuery to Add and Remove CSS Classes on Click?

Linda Hamilton
Release: 2024-11-26 03:47:11
Original
358 people have browsed it

How to Use jQuery to Add and Remove CSS Classes on Click?

How to Add and Remove Classes on Click Using jQuery?

In jQuery, you can dynamically manipulate CSS classes on elements with the addClass(), removeClass(), and toggleClass() methods. This can be useful for implementing dynamic behavior, such as adding or removing active states or highlighting menu items.

Example: Adding and Removing a Class on Click

Suppose you have a menu with

  • elements. You want to add a "current" class to the clicked element while removing it from all other elements. This ensures that only one element has the "current" class at a time.

    Here's a jQuery solution:

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

    This code uses event delegation to attach a click handler to all

  • elements within the container with ID "menu." When an element is clicked, it adds the "current" class to itself and removes the same class from all its siblings using the siblings() method.

    Additional Consideration: Initializing the "current" Class

    Initially, you'll want to set the "current" class on one of the menu items. You can do this using:

    $('#about-link').addClass('current');
    Copy after login

    This adds the "current" class to the element with the ID "about-link," ensuring it starts off as the active item.

    Improved Solution

    Here's an improved solution that simplifies the code:

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

    This works similarly to the previous code but targets the elements within

  • items. By default,
  • elements do not have href attributes, so the click event is not triggered on them directly.

    The above is the detailed content of How to Use jQuery to Add and Remove CSS Classes on Click?. 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