Search code examples
jqueryaccordionslidetoggle

Adding And Removing Class on Active Accordion Toggle Element


I have a Jquery Code for accordion and it's working well except I need to add/remove class on active trigger. What I mean is, when the H2 element is clicked, I need a class "accordion-toggled" added to it. The code shown here adds the class to all H2 elements when toggled and I only need it added to active H2.

I could use some help on this.

$(document).ready(function(){
   $('div.accordion-content> p').hide();  
   $('div.accordion-content> h2').click(function() {
     $(this).next('p').slideToggle('fast')
     .siblings('p:visible').slideUp('fast');
     $('div.accordion-content> h2').toggleClass('accordion-toggled');
   });
});

HTML

<div class="accordion-content">
   <h2>Question 1</h2>
   <p>Some answers for question 1</p>
   <h2>Question 2</h2>
   <p>Some answers for question 2</p>
   <h2>Question 3</h2>
   <p>Some answers for question 3</p>
</div>

Solution

  • With using the this keyword you can reference the element you just clicked:

    $(document).ready(function(){
       $('div.accordion-content> p').hide();  
       $('div.accordion-content> h2').click(function() {
         $(this).next('p').slideToggle('fast')
         .siblings('p:visible').slideUp('fast');
          $(this).toggleClass('accordion-toggled');
          $('div.accordion-content> h2').not(this).removeClass('accordion-toggled');
       });
    });
    .accordion-toggled{
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="accordion-content">
       <h2>Question 1</h2>
       <p>Some answers for question 1</p>
       <h2>Question 2</h2>
       <p>Some answers for question 2</p>
       <h2>Question 3</h2>
       <p>Some answers for question 3</p>
    </div>