0
Q:

toggle class jquery


$("button").click(function(){
  $("p").toggleClass("main");
 });
 
7
$(".nav-link").click(function () {
  // If the clicked element has the active class, remove the active class from EVERY .nav-link>.state element
  if ($(this).hasClass("active")) {
    $(".nav-link").removeClass("active");
  }
  // Else, the element doesn't have the active class, so we remove it from every element before applying it to the element that was clicked
  else {
    $(".nav-link").removeClass("active");
    $(this).addClass("active");
  }
});
1
$( "#foo" ).toggleClass( 'className', addOrRemoveOptional );
10
$('.click-class').click(function() {
    $('.class-toggle').toggle();
    $('.class-toggle').toggleClass('add-class');
})
0
Definition and Usage
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

However, by using the "switch" parameter, you can specify to only remove, or only add a class name.

Syntax
$(selector).toggleClass(classname,function(index,currentclass),switch)

Example
Toggle between adding and removing the "main" class name for all <p> elements:
$("button").click(function(){
  $("p").toggleClass("main");
 });
 
1

New to Communities?

Join the community