Reputation: 323
I'm coding a simple accordion using HTML5 and jQuery to animate the opening and closing states.
I want to visually show users when sections of the accordion are opened or closed using font awesome icons. At the moment I have managed to achieve this using the following code below:
$(this).find('i').toggleClass('fa fa-plus-circle fa fa-minus-circle')
The only issue that I'm having trouble figuring out how to reset each sections icon to the plus icon when not in an open state. For example, if I click Item 1 the icon will now change from a plus to a minus, great! But that problem is if I click on Item 2 or 3 the icon will not revert back to a plus.
As I have illustrated in the above screenshot, this is what I'm trying to achieve. I have used Item 1 and 3 as examples but it should work the same way for all the Items.
I've provided a JSFiddle with my syntax, and here's the code:
$(document).ready(function () {
'use strict';
$('.accordian h3').click(function () {
//toggle plus and minus icons
$(this).find('i').toggleClass('fa fa-plus-circle fa fa-minus-circle');
//slide up all the list items
$('.accordian ul ul').slideUp();
//slide down the list itmes below the h3 clicked - only if it's closed
if (!$(this).next().is(':visible')) {
$(this).next().slideDown();
}
});
});
@import url("http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css");
html, body {
background-color: #ccc
}
.accordian {
margin: 0 auto;
color: #000;
}
.accordian h3 {
padding: 15px;
line-height: 1px;
cursor: pointer;
border: 1px solid #000;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
}
/*iconfont styles*/
.accordian h3 i {
font-size: 18px;
margin-right: 10px;
}
.accordian li {
list-style-type: none;
}
/*Lets hide the non active li's by default*/
.accordian ul ul {
display: none;
}
.accordian li.active ul {
display: block;
}
<div class="accordian">
<ul>
<li>
<h3><i class="fa fa-plus-circle"></i>Item 1</h3>
<ul>
<li>
Item 1
</li>
</ul>
</li>
<li>
<h3><i class="fa fa-plus-circle"></i>Item 2</h3>
<ul>
<li>
Item 2
</li>
</ul>
</li>
<li>
<h3><i class="fa fa-plus-circle"></i>Item 3</h3>
<ul>
<li>
Item 3
</li>
</ul>
</li>
</ul>
</div>
Upvotes: 2
Views: 1375
Reputation: 24001
$(document).ready(function () {
'use strict';
$('.accordian h3').click(function () {
//toggle plus and minus icons
$('.accordian h3 i').addClass('fa-plus-circle').removeClass('fa-minus-circle');
$(this).find('i').toggleClass('fa fa-plus-circle fa fa-minus-circle');
//slide up all the list items
$('.accordian ul ul').slideUp();
//slide down the list itmes below the h3 clicked - only if it's closed
if (!$(this).next().is(':visible')) {
$(this).next().slideDown();
}else{
$('.accordian h3 i').addClass('fa-plus-circle').removeClass('fa-minus-circle');
}
});
});
Upvotes: 4