Marek Has Marek Has - 4 months ago 51
jQuery Question

Accordion menu with rotating arrows

I have created a simple accordion with rotating arrows on click. It works fine with one exception :


  • I have a few collapsible item and if I click the first one it works ok. But clicking the other one do not rotate the previous icon to the default state.



How to make arrow to come back to the default state when clicking the other collapsible item?



$(function() {
$('.arrow-r').on('click', function() {
$(this).find('.fa-angle-down').toggleClass('rotate-element');
})
})

.rotate-element {
@include transform (rotate(180deg));
}
.fa-angle-down {
&.rotate-icon {
position: absolute;
right: 0;
top: 17px;
@include transition (all 150ms ease-in 0s);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="collapsible collapsible-accordion">
<li><a class="collapsible-header arrow-r"> Menu 1<i class="fa fa-angle-down rotate-icon"></i></a>
<div class="collapsible-body">
<ul>
<li><a>Item 1</a>
</li>
<li><a>Item 2</a>
</li>
</ul>
</div>
</li>
<li><a class="collapsible-header arrow-r"> Menu 2<i class="fa fa-angle-down rotate-icon"></i></a>
<div class="collapsible-body">
<ul>
<li><a>Item 1</a>
</li>
<li><a>Item 2</a>
</li>
</ul>
</div>
</li>
<li><a class="collapsible-header"> Menu 3</a>
<div class="collapsible-body">
<ul>
<li><a>Item 1</a>
</li>
<li><a>Item 2</a>
</li>
</ul>
</div>
</li>




Answer

Please try this:

$(function() {
  $('.arrow-r').on('click', function() {
    //Reset all
    $('.arrow-r').find('.fa-angle-down').removeClass('rotate-element');
    //Rotate the clicked one
    $(this).find('.fa-angle-down').addClass('rotate-element');
  })
})
Comments