Darren Bachan
Darren Bachan

Reputation: 743

how to make toggleClass apply only to the element clicked on

I am trying my best to word this, this probably exists already but I am not sure the language necessary to find it.

I have an accordion that's being outputted by a list. I'm trying to make it so when the list item is clicked on, the icon animates.

$('[data-toggle=collapse]').on('click', function() {
        $('[data-toggle=collapse]').not(this).removeClass('collapsed');
        $('.plus-minus-toggle').toggleClass('collapsed');
    });

I attempted, from the Googling I had done, to achieve this, but what's happening is if I click on any list item with [data-toggle=collapse] then all divs with .plus-minus-toggle toggle collapsed. I only want the [data-toggle=collapse] I clicked on to toggle collapsed. I am not sure how to single this out for once instance.

Update

I have a similar piece of code that's related, is it possible to tie them in to my OP? Or should they remain separate?

$(document).on('click', '[data-toggle=collapse] .fa', function(e) {
        e.stopPropagation();
    });

Update #2

<div class="tab-pane active" id="tab2">
  <div class="panel-group" id="help-accordion-2">
    <div class="panel panel-default panel-help">
      <a href="#post-surgery-add-case-add-cases-work" data-toggle="collapse">
        <div class="panel-heading">
          <h2>What is an add-on case? How to add-on cases work?</h2>
          <div class="plus-minus-toggle collapsed"></div>
        </div>
      </a>

      <div id="post-surgery-add-case-add-cases-work" class="collapse">
        <div class="panel-body">
          <p>Lorem Ipsum</p>
        </div>
      </div>
    </div>
  </div>
</div>

Here's a sample of the HTML being used.

Update #3

$('[data-toggle=collapse]').on('click', function() {
    $('[data-toggle=collapse]').not(this).removeClass('collapsed');
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
});

This code accomplished what I wanted.

Upvotes: 2

Views: 57

Answers (2)

Anonymous
Anonymous

Reputation: 1990

$('[data-toggle=collapse]').on('click', function(e) {
        $('[data-toggle=collapse]').not(this).removeClass('collapsed');
        $('.plus-minus-toggle').toggleClass('collapsed');
        e.stopPropogation();
});

Upvotes: 0

carlosp120
carlosp120

Reputation: 76

Like this:

$('[data-toggle=collapse]').on('click', function() {
    $('[data-toggle=collapse]').not(this).removeClass('collapsed');
    $(this).toggleClass('collapsed');
});

Hope this helps.

Upvotes: 1

Related Questions