New to Jquery. Tell me how to improve this FAQ code.
I would like tips on how this might be improved. I just started learning jquery today so I'm interested in learning any methods long-time users have figured out.
This is for showing\hiding content based on selectors, like you might use in a FAQ page.
-
$(function() {
var toggleSelector = 'h2';
var contentSelector = 'p';
var eventType = 'click';
var showType = 'toggle'; // show or toggle
var closeOthers = false;
var startState = 'hide' // hide or show;
$('.faq').each(function() {
var contents = $(contentSelector, this)[startState]();
$(toggleSelector, this).each(function(i) {
$(this).bind(eventType, function(event) {
$(contents[i])[showType]("fast");
if (closeOthers) {
$(contents).each(function(j) {
if (j != i && $(this).is(":visible")) {
$(this).hide("fast");
}
});
}
});
});
});
});
<div class="faq">
<h2>Question</h2>
<p>Answer</p>
<h2>Question</h2>
<p>Answer</p>
<h2>Question</h2>
<p>Answer</p>
<h2>Question</h2>
<p>Answer</p>
</div>