Alex Maro
Alex Maro

Reputation: 3

Remove class from sibling when added to (this), toggle (this)

I am building a small gallery that expands and contracts. The parent div expands and the children expand. I want the class "open" to be removed when a sibling is clicked but also want to be able to remove "open" from all ".panel" divs when the currently "open" div is clicked. Also the parent div expands with a class ".full".

$(document).ready(function() {
  $('.panel').on('click', function(e) {
    $('.panel').removeClass("open");
    $(this).toggleClass("open"); //this is not working
    if ($(this).hasClass('open')) {
      $(this).parent().addClass("full");
    } else {
      $(this).parent().removeClass("full");
    }
  });
});

Upvotes: 0

Views: 23

Answers (1)

Barmar
Barmar

Reputation: 782148

You're removing the class from all .panel elements, which includes the one that the user clicked on. You need to exclude the current element:

$('.panel').not(this).removeClass("open");

Upvotes: 2

Related Questions