JQuery - toggle & removeClass

Easy, but I can’t understand. I have a link called #title, and when you click on it, it toggles a div called #content. This works fine, but also, I am adding an “active” class to my #title link, and I cannot get rid of it, even with removeClass.

See the code above and a link to an example (the title should be red ONLY with the extension #content, not all the time).

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

http://jsfiddle.net/vY3WY/

+6
source share
5 answers

You can use the toggleClass function along with the toggle.

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

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

Or you can use a more robust version that will add a class if the content is visible and deleted otherwise.

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

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

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" with hasClass and remove it, if any. Add it if it is not.

Or you can use toggleClass to hide all this logic.

+6
source

A compact and still readable (I think) solution:

 $('#title').click(function() { var isContentVisible=$('#content').toggle().is(':visible'); $(this).toggleClass('active', isContentVisible); }); 

Live demo

It toggles #content and checks if it is visible or not. Then it switches the class to #title based on the result. There may also be a one-line function, but it does not meet my expectations of readability.

+5
source

another solution to hide the current value with a different value

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

});

Click here ! This works with link links .

0
source

I think this is the most suitable way to do this.

$(this).toggleClass('active').siblings().removeClass('active');

0
source

Source: https://habr.com/ru/post/885445/


All Articles