Skip to content

Instantly share code, notes, and snippets.

@madfriend
Created Sep 10, 2015
Embed
What would you like to do?
my jquery snippets
$.fn.mapGetter = function(prop) {
return $(this).map(function(i, e) {
return $(e).attr(prop);
}).get();
};
$.fn.filterByAttr = function(attr, val) {
return $(this).filter(function(i, e) {
return $(e).attr(attr) == val;
});
};
var originalAddClassMethod = $.fn.addClass;
var originalRemoveClassMethod = $.fn.removeClass;
$.fn.addClass = function() {
var result = originalAddClassMethod.apply(this, arguments);
$(this).trigger('cssClassAdded', arguments);
return result;
}
$.fn.removeClass = function() {
var result = originalRemoveClassMethod.apply(this, arguments);
$(this).trigger('cssClassRemoved', arguments);
return result;
}
// $(el).syncByClass(other-el)
// when el gets new classes, other-el gets them too
$.fn.syncByClass = function(that) {
$(this).on('cssClassAdded', function(e, className) {
if ($(e.target).is(this)) $(that).addClass(className);
});
$(this).on('cssClassRemoved', function(e, className) {
if ($(e.target).is(this)) $(that).removeClass(className);
});
};
$.fn.removeClassRegex = function(regex) {
return $(this).removeClass(function(index, classes) {
return classes.split(/\s+/).filter(function(c) {
return regex.test(c);
}).join(' ');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment