Reputation: 652
I am trying to add an arrow to my accordions to show whether it's open or closed. Both for the main accordion and the nested accordion. (For now I've used text).
The code works fine when you click on the current open, or parent open accordion. But it goes wonky when you click on something else without closing the current open item.
I have tried to add a removeClass everywhere in the JS that is says 'slideUp', and an addClass where it says 'slideDown'. I assumed this would work as the slideUp/Down controls whether the div shows.
I'm missing something, but not sure what.
http://codepen.io/anon/pen/WQJYvj
JS
<script>
$(document).ready(function () {
var parentDivs = $('.nestedAccordion div'),
childDivs = $('.nestedAccordion h6').siblings('div');
$('.nestedAccordion h5').click(function () {
parentDivs.slideUp();
$(this).removeClass( "open" );
if ($(this).next().is(':hidden')) {
$(this).next().slideDown();
$(this).addClass( "open" );
} else {
$(this).next().slideUp();
$(this).removeClass( "open" );
}
});
$('.nestedAccordion h6').click(function () {
childDivs.slideUp();
$(this).removeClass( "open" );
if ($(this).next().is(':hidden')) {
$(this).next().slideDown();
$(this).addClass( "open" );
} else {
$(this).next().slideUp();
$(this).removeClass( "open" );
}
});
});
</script>
HTML
<div class="nestedAccordion">
<h5>ingredients found in our products</h5>
<div style="display:none;">
<h6>Lavender</h6>
<div>Hair</div>
<h6>Panthenol (Plant derived)</h6>
<div>Hair</div>
</div>
</div>
<hr/>
<div class="nestedAccordion">
<h5>ingredients NOT found in our products</h5>
<div style="display:none;">
<h6>Lavender</h6>
<div>Hair</div>
<h6>Panthenol (Plant derived)</h6>
<div>Hair</div>
</div>
</div>
CSS
.nestedAccordion h5::before {
color: red;
content: "down arrow ";
}
.nestedAccordion h5.open::before {
color: orange;
content: "up arrow ";
}
.nestedAccordion h6::before {
color: blue;
content: "down arrow ";
}
.nestedAccordion h6.open::before {
color: lime;
content: "up arrow ";
}
Upvotes: 1
Views: 515
Reputation: 8858
Try this :
var parentDivs = $('.nestedAccordion div'),
childDivs = $('.nestedAccordion h6').siblings('div');
$('.nestedAccordion h5').click(function () {
$('.nestedAccordion h5').removeClass("open");
$('.nestedAccordion h6').removeClass("open");
parentDivs.slideUp();
// $(this).removeClass( "open" );
if ($(this).next().is(':hidden')) {
$(this).next().slideDown();
$(this).addClass( "open" );
} else {
$(this).next().slideUp();
$(this).removeClass( "open" );
}
});
$('.nestedAccordion h6').click(function () {
$('.nestedAccordion h6').removeClass("open");
childDivs.slideUp();
// $(this).removeClass( "open" );
if ($(this).next().is(':hidden')) {
$(this).next().slideDown();
$(this).addClass( "open" );
} else {
$(this).next().slideUp();
$(this).removeClass( "open" );
}
});
http://jsfiddle.net/3k0vLdt4/1/
Upvotes: 1