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/
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');
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With