Monday, May 18, 2009

jQuery toggleClass

You can extend jQuery to swap classes with a toggleClass as shown below:

//extend jquery
(function($) {
$.fn.toggleClass = function(check, replace) {
return this.each(function() {
if ($(this).hasClass(check)) {
$(this).removeClass(check);
$(this).addClass(replace);
} else {
if ($(this).hasClass(replace))
$(this).removeClass(replace);
$(this).addClass(check);
}
});
};
})(jQuery);


So you can do stuff like this:

<input type="button" value="Toggle"
onclick="$('#myDiv').toggleClass('expanded','collapsed')"/>

No comments:

Post a Comment