Created
July 16, 2012 15:37
-
-
Save borestad/3123387 to your computer and use it in GitHub Desktop.
A jQuery method for switching classes in the DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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