Switch classes in jQuery
Posted by Jaggi on August 24th, 2009jQuery comes with a nice little function called toggleClass() which is good in certain cases, for example when you want to turn a class on or off. However there have been many circumstances where i wanted to swop a class with another. To get around this i wrote this function:
jQuery.fn.switchClass = function(a, b) {
elm = $(this);
if ( elm.hasClass(a) ) {
elm.removeClass(a).addClass(b);
} else {
elm.removeClass(b).addClass(a);
}
};
All you need to do to use it is call the function and pass in the names of the two classes. E.g:
$('a').click( function() {
$('div').switchClass('up', 'down');
});
This will remove the class up and add the class down, when clicked again it will do the opposite therefore not needing to call it again.
Note: theres a function which can achieve this in jQuery UI however if you don’t want to load a entire new library for a simple function then use this, since they’re called the same you should use one OR the other.

Recent Comments