Question

I have an accordion and unfortunately there is no active or current class assigned to the qafp-faq div which serves as a container for each item.

My main objective is to add icons indicating toggle state.

I added:

 $( ".qafp-faq-anchor" ).click(function() {
$( this).find( ".fa-caret-right" ).toggleClass( "open", 1000 );
return false;
});

Which works great for allowing me to target the title if I open a div via the title, but not when the accordion behavior hides an open div when clicking another div.

You can see the problem here: http://jsfiddle.net/Qzwvr/2/

The solution I'm really after is how I can add a class to the qafp-faq div whenevr it is toggled.

I've definitely been learning a lot about jQuery and hope I can figure this out. Thank you.

Was it helpful?

Solution

The easiest way to do this would be to change it from toggleClass into a removeClass and addClass

$(".qafp-faq-anchor").click(function () {
    // Remove open class if this is open
    if($(this).find('.fa-caret-right').hasClass('open')) {
        $(this).find('.fa-caret-right').removeClass('open');
    }
    else {
        // Removes open class no matter where it is
        $('.open').removeClass( "open", 1000 ); 
        // Adds open class to clicked element
        $(this).find(".fa-caret-right").addClass("open", 1000);
        return false;
    }
});

Updated jsFiddle

If you have multiple accordions you could make the selector for removing the open class more specific if you want multiple open at the same time

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top