Skip to content

Instantly share code, notes, and snippets.

@nekman
Last active January 4, 2016 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nekman/8630823 to your computer and use it in GitHub Desktop.
Save nekman/8630823 to your computer and use it in GitHub Desktop.
jQuery attribute matcher.
/**
* http://plnkr.co/edit/Mou8b94hzmuIVjd7b63w?p=preview
*/
(function(global, factory) {
// CommonJS
if (typeof module === 'object') {
module.exports = factory(require('jquery'));
} else if (typeof global.define === 'function') {
// AMD
define(['jquery'], factory);
} else {
// Loaded by <script> tag
factory(global.jQuery);
}
}(this, function($) {
'use strict';
var findSelector = '[{{attr}}="{{search}}"]',
defaults = {
on: 'mouseenter',
off: 'mouseleave',
attr: 'data-highlight',
onmatch: 'match',
onleave: 'leave'
};
function Matcher(settings) {
this.settings = settings;
this.$parent = settings.$parent;
this.$nodes = settings.$nodes;
this.findSelector = findSelector.replace(/{{attr}}/, settings.attr);
this.$nodes
.on(settings.on, this.handle(this, settings.onmatch))
.on(settings.off, this.handle(this, settings.onleave));
}
Matcher.prototype.handle = function(self, eventName) {
return function() {
var search = $(this).attr(self.settings.attr),
$matches = self.$parent.find(self.findSelector.replace(/{{search}}/, search));
$matches.length && self.$parent.trigger(eventName, [$matches]);
};
};
$.fn.attrMatcher = function(options) {
if (!this.length) {
return this;
}
var settings = $.extend(defaults, options || {});
$.extend(settings, {
$parent: settings.parent instanceof jQuery ? settings.parent : this.parent(),
$nodes: this
});
new Matcher(settings);
return this;
};
}));
// Start
$(document).ready(function() {
var $parent = $('table');
$parent
.on('match', function(e, $matches) {
$matches.addClass('highlight');
})
.on('leave', function(e, $matches) {
$matches.removeClass('highlight');
})
.find('tr')
.attrMatcher({
parent: $parent
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment