Moises Pachon
Moises Pachon

Reputation: 85

jQuery: Remove class if the same element is clicked

I have some elements that expand (it is similar or the same as an encoder), when it has the "Active" class it expands and when it touches another element the "Active" class is removed.

The problem arises at the suggestion of a friend who wants the same item that was opened to close by clicking on the same item and not another item, I hope it makes me understand.

I want to do what my friend says because he has some logic, but I really don't know how to do it

I have Jquery's function like this:

(function($) {
  $("#product-accordion article")
    .click(function() {
      $(this).addClass("active");
      $(this).siblings().removeClass("active");
    });
})(jQuery);

Upvotes: 0

Views: 668

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370769

Check hasClass to see if the clicked element is active, and only add the class if it's not:

$("div").click(function() {
  const $this = $(this);
  if (!$this.hasClass('active')) {
    $this.addClass("active");
  } else {
    $this.removeClass('active');
  }
  $this.siblings().removeClass("active");
});
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>click</div>
<div>click</div>
<div>click</div>
<div>click</div>

You can also use .toggleClass on the clicked element:

$("div").click(function() {
  const $this = $(this);
  $this.toggleClass("active");
  $this.siblings().removeClass("active");
});
.active {
  background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>click</div>
<div>click</div>
<div>click</div>
<div>click</div>

Upvotes: 2

Related Questions