Reputation: 681
I'm using this particular script for specific expand/collapse items and have decided i'd like to be able to toggle multiple objects on the same page but im not sure exactly how do make that happen. Can anybody provide any insight?
$('#faq_info_header').click(function() {
$('#faq_info_exp').toggle();
var arrow = $('#faq_info_header').find('.fa');
if (arrow.hasClass('fa-arrow-right')) {
arrow.removeClass('fa-arrow-right');
arrow.addClass('fa-arrow-down');
} else if (arrow.hasClass('fa-arrow-down')) {
arrow.removeClass('fa-arrow-down');
arrow.addClass('fa-arrow-right');
}
return false;
});
HTML as requested:
<a id="faq_info_header">This is the question? <i class="fa fa-arrow-right"></i></a>
<div id="faq_info_exp" style="display:none;">This is the hidden content</div>
Upvotes: 1
Views: 2227
Reputation: 17407
You can use toggleClass (more here http://api.jquery.com/toggleClass/) by replacing your entire if statement with:
arrow.toggleClass('fa-arrow-right fa-arrow-down');
Okay, now I think I understand the question. Here is a fiddle
HTML:
<div class="faqs">
<div class="faq_item">
<p>This is the question 1? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 1</div>
</div>
<div class="faq_item">
<p>This is the question 2? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 2</div>
</div>
<div class="faq_item">
<p>This is the question 3? <i class="fa fa-arrow-right"></i>
</p>
<div class="faq_info_exp">This is the hidden content 3</div>
</div>
</div>
JS:
$('.faqs').on('click', '.faq_item', function () {
$(this).children('.faq_info_exp').toggle();
$(this).find('i').toggleClass('fa-arrow-right fa-arrow-down');
});
CSS:
.faq_info_exp {
display: none;
}
Basically what I did was:
$(this)
to refer to it easily.$(this).children('.faq_info_exp').toggle();
finds the direct child element with the class faq_info_exp and toggles it.$(this).find('i').toggleClass('fa-arrow-right fa-arrow-down');
finds the descendant element <i>
and toggles the class.Upvotes: 2