Conditionally toggle a class on a element with 1 jQuery statement
Until now if I had a an element, for example an a
tag, and I wanted to add or remove a class based on some condition I would do it like this:
if (condition)
$('a.some-link').addClass('some-class');
else
$('a.some-link').removeClass('some-class');
I've known about toggleClass for a while but I never read its documentation. You can pass a boolean as the second parameter to toggleClass that will determine whether the given class is added or removed, like so:
$('a.some-link').toggleClass('some-class', condition);
Written by Dustin Haffner
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Css
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#