jquery class toggle code example

Example 1: toggle class javascript and jquery

$('.click-class').click(function() {
    $('.class-toggle').toggle();
    $('.class-toggle').toggleClass('add-class');
})

Example 2: toggle jquery remove others

$(".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");
  }
});

Example 3: jquery toggle class

$( "#foo" ).toggleClass( 'className', addOrRemoveOptional );

Example 4: jquert toggleClass condition

// add class [class-name] if condition is true
// or else remove it
$('#foo-bar').toggleClass('class-name', condition)

Example 5: toggle class jquery

toggleClass