Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - toggle & removeClass

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/

like image 425
Wordpressor Avatar asked Apr 07 '11 17:04

Wordpressor


2 Answers

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');   
    }
});
like image 149
Gazler Avatar answered Jan 02 '23 09:01

Gazler


This version works.

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

Check for the presence of 'active' using hasClass and remove it if it is there. Add it if it is not.

Or you could use toggleClass to hide all that logic.

like image 26
justkt Avatar answered Jan 02 '23 08:01

justkt