Andy Andy
Andy Andy

Reputation: 299

Issue with removing jquery class

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(); }
        });
    });
});

JSFiddle

jQuery(".active").removeClass(); }

fixes half of the issue

Upvotes: 0

Views: 41

Answers (1)

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15837

it is actually .removeClass() that you have to try..!!

JS FIDDLE

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" );
        });
    });
});

DEMO FIDDLE

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('+');
                }
    
    
            });
        });
    });
    

    updated fiddle

    Upvotes: 2

    Related Questions