Need a bit help. Still a beginner at jQuery…
I have a product package comparison table. First column contains the functions. If I click on a function it opens and shows the description of the function in accordion style, and makes the function name bold (adds class ‘active’) as the active accordion header.
By default all the accordions are closed. I want only 1 accordion to be open at the same time so if the visitor clicks on another the previous one automatically closes. I made this work. The problem comes up when I click the Accordion head again to close it because it will open instantly again, however it removes the active class.
How can I close the 1 accordion which is opened without making it open again instantly (thought about an if statement, but not sure how to make it work…)?
Here is the html:
<tr>
<td><div class="accordion"><h4><a href="javascript:(void)">Accordion head</a></h4><div class="module-desc">Service description</div></div></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/simeimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
</tr>
<tr>
<td><div class="accordion"><h4><a href="javascript:(void)">Accordion head</a></h4><div class="module-desc">Service description</div></div></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
</tr>
<tr>
<td><div class="accordion"><h4><a href="javascript:(void)">Accordion head</a></h4><div class="module-desc">Service description</div></div></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
<td><img src="assets_wm/images/someimg.png" alt="pipa" /></td>
</tr>
Here is the jQuery code:
$(document).ready(function(){
$(".module-desc").hide();
$(".accordion h4").click(function(){
$(".accordion").find(".module-desc").hide("fast");
var thisBlock = $(this).parent().index('.accordion');
$(".accordion").find(".active").not($(this)).removeClass("active");
$(this).toggleClass("active").next().slideToggle("fast");
$(this).parent().toggleClass("activeToggle").siblings()
.removeClass("activeToggle").children(".module-desc").hide("fast");
return false;
});
});
JsFiddle link:
http://jsfiddle.net/5QT6A/
Only service description should be hidden. The images need to stay visible even after the accordion closes.
Just realised there’s a simpler way than my previous answer. First toggle the clicked items active class and do a slide toggle on the next item (the content). Then for everything else that is not the clicked item, remove the active class and slide the next item (the content) up.
Example: jsfiddle