2

I am creating accordian menu with simple js. How can I add and remove active class on click open/close?

<div class="mobile-categories">
    <h4 class="mcategory-toggle">Vehicles</h4>
    <ul class="msub-categories">
        <li>Option 1</li>
        <li>Option 2</li>
        <li>Option 3</li>
    </ul>
    <h4 class="mcategory-toggle">Education</h4>
    <ul class="msub-categories">
        <li>Option 10</li>
        <li>Option 20</li>
        <li>Option 30</li>
    </ul>
    <h4 class="mcategory-toggle">Shops</h4>
    <ul class="msub-categories">
        <li>Option 14</li>
        <li>Option 25</li>
        <li>Option 36</li>
    </ul>
</div>

a fiddle

3 Answers 3

2

You can use toggleClass method.

  $(document).ready(function($) {
                $('.mobile-categories').find('.mcategory-toggle').click(function(){

            var self = $(this);

            //Expand or collapse this panel
            self.next().slideToggle('fast');

            //Remove active class for all element, except the current selected item
            $('.mcategory-toggle').not(self).removeClass('active');

            //Toggle active class for the current element
            self.toggleClass('active');

                  //Hide the other panels
            $(".msub-categories").not(self.next()).slideUp('fast');

                });
      });

You can see Working Fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Add jQuery toggle class method to your click function:

$(this).toggleClass('active');

Comments

0

Add remove class on Click Using jQuery

$(document).ready(function(){
$('.btn').on('click',function(){
      if($('.box').hasClass('current')){
        $('.box').removeClass('current');
      }else{
        $('.box').addClass('current');
      }
   });
 });

1 Comment

Think this one is understandable due to the title but I'd recommend reading stackoverflow.com/help/how-to-ask . even a short well-thought-out sentence can make the question much easier to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.