jQuery - toggle & removeClass

Wordpressor picture Wordpressor · Apr 7, 2011 · Viewed 34.9k times · Source

An easy one, but I can't figure it out. I have a link called #title and when you click it it toggles div called #content. This works perfectly, but in addition I'm adding "active" class to my #title link and I can't get rid of it, even with removeClass.

See code above and example link (the title should be red ONLY when the #content is expanded, not all the time).

$('#title').click(function() {
    $(this).addClass('active');
    $('#content').toggle();
}), function() { 
    $(this).removeClass('active');
};

http://jsfiddle.net/vY3WY/

Answer

Gazler picture Gazler · Apr 7, 2011

You can use the toggleClass function along with toggle.

http://jsfiddle.net/vY3WY/1/

$('#title').click(function() {
    $(this).toggleClass('active');
    $('#content').toggle();
});

Or you can use a more robust version which will ensure that the class is added if the content is visible and removed otherwise.

http://jsfiddle.net/vY3WY/6/

$('#title').click(function() {
    $('#content').toggle();
    if ($('#content:visible').size() != 0)
    {
         $(this).addClass('active');   
    }
    else
    {
         $(this).removeClass('active');   
    }
});