Skip to content

Instantly share code, notes, and snippets.

@Naddiseo
Last active December 19, 2015 16:59
Show Gist options
  • Save Naddiseo/5988092 to your computer and use it in GitHub Desktop.
Save Naddiseo/5988092 to your computer and use it in GitHub Desktop.
This jquery plugin allows bulk editing of classes on elements. Use like: $('#myelement').changeClass('+one -two !three'); This unconditionally adds class `one`, unconditionally removes class `two`, and toggles class `three`
/*
//@ sourceURL=static/js/lib/jquery.hacks.js
*
* from https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
*/
(function(factory) {
if ( typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
$.fn.changeClass = function(classes_string) {
var parts = classes_string.split(' ');
var worker_fn = function(el) { return $(el); };
var add_fn = function(c, action) { return function(el) { return action(el).addClass(c); }; };
var remove_fn = function(c, action) { return function(el) { return action(el).removeClass(c); }; };
var toggle_fn = function(c, action) { return function(el) { return action(el).toggleClass(c); }; };
$.each(parts, function() {
var c = this[0];
var action = add_fn;
var klass = this;
if (c == '-' || c == '+' || c == '!') {
action = (c == '-' ? remove_fn : (c == '!' ? toggle_fn : add_fn));
klass = this.slice(1);
}
worker_fn = action(klass, worker_fn);
});
return this.each(function() {
return worker_fn(this);
});
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment