hendy0817
hendy0817

Reputation: 1079

Return to normal state after jquery add / remove class

I have an accordion with three buttons that open collapse content. I've got it working where when I click each button they open correctly and the "plus sign" changes to "minus sign" with removeClass(), addClass(). Now I would like them to return to the original state with the "plus sign" when clicked again and content is closed.

I tried conditional if else but can't seem to get it working. It broke the accordion when using that method.

HTML:     
<div class="accordion--one">
                    <button class="btn accordion-btn" type="button" data-toggle="collapse"
                            data-target="#Accordion1" aria-expanded="false"
                            aria-controls="Accordion1"><i class="fas fa-plus"></i>
                    </button>
                    <span class="title-3">test</span>
                    <div class="col collapse-content">
                        <div class="collapse multi-collapse" id="bedAccordion1">
                            <div>
                           <p><b>test</b><br>
                                test</p>
                           <p><b>test</b>><br>
                    test</p>
                           <p><b>test</b><sup>1</sup><br>
                    <br>test</p>
                            </div>
                        </div>
                    </div>
                </div>

jquery:

   $(document).ready(function () {

    $(accordionBtn).click(function(e){
        e.preventDefault();
        $(this).find('.fa-plus').removeClass('fa-plus').addClass('fa-minus');
    });
 });

Upvotes: 1

Views: 665

Answers (3)

Joshua S J
Joshua S J

Reputation: 61

The code you have given changes plus icon to minus icon. You have to do the same to change it back. A better approach would be to use toggle function.

Try this:

$(".accordion-btn").click(function(e){
   e.preventDefault();
   $(this).find('i').toggleClass('fa-plus fa-minus');
});

Upvotes: 3

confuse
confuse

Reputation: 230

You could simply use toggleClass; it will toggle add/remove depending if the value is on the element set to $(this) at the time. See documentation here: https://api.jquery.com/toggleclass/.

Use:

$(accordionBtn).click(function(e) {
    e.preventDefault();
    $(this).toggleClass('fa-plus');
    $(this).toggleClass('fa-minus');
 });

Upvotes: 0

BugsArePeopleToo
BugsArePeopleToo

Reputation: 2996

Hard to know for sure without seeing your HTML structure, but I imagine you want something like this:

$(accordionBtn).click(function(e){
  e.preventDefault();
  if ($(this).hasClass('.fa-plus')) {
    $(this).removeClass('fa-plus').addClass('fa-minus');
  } else {
    $(this).removeClass('fa-minus').addClass('fa-plus');
  }
});

Upvotes: 0

Related Questions