Skip to content

Instantly share code, notes, and snippets.

@borestad
Created July 16, 2012 15:37
Show Gist options
  • Save borestad/3123387 to your computer and use it in GitHub Desktop.
Save borestad/3123387 to your computer and use it in GitHub Desktop.
A jQuery method for switching classes in the DOM
define([
'jquery'
], function ($) {
"use strict";
/**
* Method for switching between 2 or multiple classes
* @param {String} currentClasses The classes that currently exists
* @param {String} newClasses The classes we want to change to
* @param {Mixed} [expression] Expression/callback that will be evaluated.
* If it's true, it will apply the rules.
*
* @return {jQuery DomObject}
*/
$.fn.switchClasses = function(currentClasses, newClasses, expression) {
return this.each(function(){
var $this = $(this),
resultExpression = void 0;
if ($.isFunction(expression)) {
resultExpression = !!expression.call(this, currentClasses, newClasses);
}
else if (typeof expression === 'boolean') {
resultExpression = expression;
}
else if (typeof expression === 'undefined') {
resultExpression = true;
}
if (resultExpression) {
$this.removeClass(currentClasses).addClass(newClasses);
}
else {
$this.addClass(currentClasses).removeClass(newClasses);
}
});
};
return $;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment