Reputation: 134
Can anyone please tell me why this stupid code isn't working on my site? Am I crazy, or is there a conflict?
<div class="row faqbody question">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12">
<button class="question">
<h5>
Do I get to pick which chef makes my pie?
<i class="fa fa-caret-up"></i>
</h5>
</button>
</div>
</div>
<div class="row answer">
<div class="col-lg-12">
<p>Nope....</p>
</div>
</div>
</div>
</div>
$('.question').click( function() {
console.log('Question Clicked');
if ($(this).find('.fa').hasClass('fa-caret-up')) {
console.log('Has Fa-caret-up');
$(this).find('.fa').removeClass('fa-caret-up');
$(this).find('.fa').addClass('fa-caret-down');
}
if ($(this).find('.fa').hasClass('fa-caret-down')) {
console.log('Has Fa-caret-down');
$(this).find('.fa').removeClass('fa-caret-down');
$(this).find('.fa').addClass('fa-caret-up');
}
$(this).parent('div').parent('div').next('.answer').toggleClass('hidden');
});
The answer shows no problem, and the reason the caret is coded in such a funky way is because the below does not work:
$( this ).find('.fa').toggleClass('fa-caret-up fa-caret-down');
I've never seen this before. Normally simple stuff like this isn't a problem.
Thank you in advance, I'm hoping this is a simple one!
Upvotes: 1
Views: 45
Reputation: 5003
You're binding your click listener to .question
. You have a button with that class inside a div with that class. Your event is dispatching twice (once from each object), so the toggle is negated. You can see it in the console - all your log entries are doubled.
See the snippet below, the fix is basically just be more explicit with your selector:
Change:
$('.question').click(...);
To:
$('button.question').click(...)
PS... This snippet runs without FontAwesome, so I just added an X
in your <i>
tag and some styles so you could see that it changes and the classes are assigned correctly.
$('button.question').click( function() {
console.log('Question Clicked');
$(this).find('.fa').toggleClass('fa-caret-up').toggleClass('fa-caret-down');
$(this).parent('div').parent('div').next('.answer').toggleClass('hidden');
});
i.fa.fa-caret-up {
color: red;
}
i.fa.fa-caret-down {
color: blue;
}
.hidden {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row faqbody question">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12">
<button class="question"><h5>Do I get to pick which chef makes my pie? <i class="fa fa-caret-up">X</i></h5></button>
</div>
</div>
<div class="row answer hidden">
<div class="col-lg-12">
<p>Nope....</p>
</div>
</div>
</div>
</div>
Upvotes: 3