Last active
January 4, 2016 13:49
-
-
Save nekman/8630823 to your computer and use it in GitHub Desktop.
jQuery attribute matcher.
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
/** | |
* 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; | |
}; | |
})); |
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
// 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