I tried to not alter your HTML if possible, so that you wouldn't have to deal with styling headaches. Unfortunately this means the JS is a bit more hard coded than I would like.
HTML:
<div class="topCats">
<h4><a href="#" class="openBox">Most Searched Categories</a></h4>
</div>
<div id="topCatsContainer" class="accordianContent">
content 1
</div>
<div class="allCats">
<h4><a href="#" class="closed">All Categories</a></h4>
</div>
<div id="allCatsContainer" class="accordianContent">
content 2
</div>
The HTML is the same except I added a class to each of your content div.
JS:
$('#allCatsContainer').css("display", "none");
$('.topCats h4 a, .allCats h4 a').click(function() {
var content = $(this).parent().parent().next();
if(content.is(':visible')) {
content
.slideUp(500)
.addClass('closed')
.removeClass('openBox');
} else {
content
.parent()
.find('.accordianContent:visible')
.slideUp(500)
.addClass('closed')
.removeClass('openBox');
content.slideDown(500).removeClass('closed').addClass('openBox');
}
});
Basically the JS finds the content that matches the link that was clicked. If the content was visible then it just closes itself. If it wasn't visible then we close whichever was visible and open the clicked content.
If you notice I am toggling both the openBox
and closed
class, which can be redundant but I wasn't sure if your styling relied on it or not.
In general this functionality can be accomplished many ways and if you are willing to change your HTML a bit we could have the JS side look a bit more presentable :) Otherwise you can just use this implementation and avoid any styling headaches.