Have a question and answer system where the answer starts of hidden, then when the question is clicked, the answer slides down. This is working fine, but then I would like it so that if the question is then clicked again, the answer slides back up. At the moment it is just ignoring that command. The remove/add class is working so I cant think what else it can be?
HTML:
<h2 class="traverse">What subjects are covered in the Core Knowledge Sequence UK?</h2>
<p class="traversing">The Core Knowledge Sequence UK is a guideline of the fundamental skills and content to cover in English, maths, history and geography, science, music and visual arts.</p>
Jquery:
$(".traverse").click(function(){
$(this).next("p.traversing").slideDown();
$(this).removeClass('traverse');
$(this).addClass('traversed');
});
$(".traversed").click(function(){
$(this).next("p.traversing").slideUp();
$(this).removeClass('traversed');
$(this).addClass('traverse');
});
The trick is you are adding the traversed class upon the user action... after you have attached the event handler to all matches with jQuery (thus the new element isn't caught)
I'd recommend a change of approach. Keep a class on the elements that can be toggled, and just slide up/down as needed using .toggle();
e.g.
$('.collapsible').toggle(function(){
$(this).next('p.traversing').slideUp();
}, function(){
$(this).next('p.traversing').slideDown();
}
);
Here's a demo: http://jsfiddle.net/7aVkx/1/