Reputation: 299
Could anyone help me out with this?
Basically I want the script to add 'active' class to 'li' on click, and remove it on another click - well, it adds the class and automatically deletes it :-) I would really appreciate any solution.
PS. I have looked around other questions concerning this issue, but I haven't found any answer that would help me.
jQuery(document).ready(function() {
jQuery('li').each(function() {
var faq = jQuery(this), state = true, answer = faq.next('.answer').hide().css('height','auto').slideUp();
faq.click(function() {
state = !state;
answer.slideToggle(state);
faq.addClass('active',state);
if(jQuery("li").hasClass("active")) {
jQuery(".active").remove(); }
});
});
});
jQuery(".active").removeClass(); }
fixes half of the issue
Upvotes: 0
Views: 41
Reputation: 15837
it is actually .removeClass() that you have to try..!!
jQuery(document).ready(function() {
jQuery('li').each(function() {
var faq = jQuery(this), state = true, answer = faq.next('.answer').hide().css('height','auto').slideUp();
faq.click(function() {
state = !state;
answer.slideToggle(state);
faq.addClass('active',state);
if(jQuery("li").hasClass("active")) {
jQuery(".active").removeClass(); }
});
});
});
OR
using .toggleClass()
use
jQuery(document).ready(function() {
jQuery('li').each(function() {
var faq = jQuery(this), state = true, answer = faq.next('.answer').hide().css('height','auto').slideUp();
faq.click(function() {
state = !state;
answer.slideToggle(state);
faq.addClass('active',state);
$( this ).toggleClass( "active" );
});
});
});
Update
updated based on @AndyAndy 's comment :
imagine that
has a "+" icon, and on click it changes to "-" icon and answer shows up.
jQuery(document).ready(function() {
jQuery('li').each(function() {
var faq = jQuery(this), answer = faq.next('.answer').hide().css('height','auto').slideUp();
faq.click(function() {
answer.slideToggle('.active');
if($(this).text()=='+')
{
$(this).text('-');
}
else{
$(this).text('+');
}
});
});
});
Upvotes: 2