Currently experiencing an issue with my accordion functionality. I have successfully implemented code that allows for toggling one heading open at a time, but I am struggling to add an open/close image beside each heading.
At the moment, when a heading is clicked, the 'open' image is removed and a 'close' image is displayed. Now, I need to find a way to swap these classes back so that when a different heading is toggled, the appropriate image is displayed.
Below is the code I am utilizing:
JavaScript
<SCRIPT>
$("#accordion > li").click(function () {
$("#accordian li").removeClass("faq-header");
$(this).addClass("faq-header2");
if (false == $(this).next().is(':visible')) {
$('#accordion > ul').slideUp(250);
$('#accordion > ul').addClass('faq-header');
$(this).removeClass("faq-header");
}
$(this).next().slideToggle(300);
});
$('#accordion > ul:eq(0)').show();
</SCRIPT>
CSS
#accordion {
list-style: none;
margin-left:-38px;
}
#accordion ul:eq {
background-image:url(../img/faq-open.gif);
background-repeat:no-repeat;
background-position:right;
padding-right:20px;
}
#accordion li{
display: block;
background-color: #FFF;
font-weight: bold;
cursor: pointer;
}
.faq-header {
text-align:left;
background-image:url(../img/faq-close.gif);
background-repeat:no-repeat;
background-position:right;
margin-right:20px;
}
.faq-header2 {
text-align:left;
background-image:url(../img/faq-open.gif);
background-repeat:no-repeat;
background-position:right;
margin-right:20px;
}
#accordion ul {
list-style: none;
display: none;
}
#accordion ul li{
font-weight: normal;
cursor: auto;
background-color: #fff;
border-bottom:1px solid #999;
margin-left:-38px !important;
}
I have successfully swapped out classes by using
$("#accordian li").removeClass("faq-header");
to remove one class and $(this).addClass("faq-header2");
to add another.
However, I am now facing the task of removing .faq-header2
and adding back .faq-header
once the selected section is no longer active. It seems like a straightforward if function is needed, but I am having trouble figuring out the code for it. Any help would be appreciated.