Reputation: 4880
I'm trying to create a FAQ page where a question turns to red when clicked and it's answer slides down, while all the other answers slide up. So at any one time only one answer is open, and only if open it's question will be highlighted red.
This is probably quite simple to achieve but I don't have much experience with javascript... So far everything is working fine if I click on different questions, but clicking on the same question while it is open will close it and then re-open it:
window.toggle_info = $ ->
$('.toggle-button').click ->
$('.toggle-button').removeClass("red-reply") unless $(this).hasClass('red')
$('.toggle-info').slideUp("slow")
$(this).next('.toggle-info').slideToggle("slow")
$(this).toggleClass("red")
I've tried using .not('red')
.not('.red')
:not('red')
in various ways on the $('.toggle-info').slideUp("slow")
line but it's not working.
The color toggle is working fine in all cases.
Thanks for your time :)
Upvotes: 0
Views: 1353
Reputation: 434785
This part:
$('.toggle-info').slideUp("slow")
$(this).next('.toggle-info').slideToggle("slow")
applies slideUp
to all of the .toggle-info
elements including $(this).next('.toggle-info')
. So you close them all and then slideToggle
the .toggle-info
the follows the .toggle-button
that you just clicked. The slideUp
will leave all of them closed and then the slideToggle
will open the .toggle-info
that you just closed.
If you wanted to be able to close a panel by click the .toggle-button
of an open one, then you could do this:
$next = $(this).next('.toggle-info');
$('.toggle-info').not($next).slideUp("slow")
$next.slideToggle("slow")
The not
call just removes $next
from the elements that slideUp
will be applied to. And if you wanted the red
only on open .toggle-button
s then you could do something like this:
$next = $(this).next('.toggle-info');
$('.toggle-info')
.not($next)
.slideUp("slow")
.prev('.toggle-button')
.removeClass('red');
$next.slideToggle("slow")
$(this).toggleClass("red")
Demo: http://jsfiddle.net/ambiguous/TEb2A/1/
I don't see anything that adds .red-reply
so I've left out of the demo; presumably you have some code elsewhere that is doing things with that class.
Upvotes: 1
Reputation: 4880
I mess with this script for ages but of course I get the answer 5 minutes after posting here :/
I changed it to $(this).next('.toggle-info').slideToggle("slow") unless $(this).hasClass('red-reply')
and it works.
Still not sure why it wouldn't work before though...
Upvotes: 0