Skip to content

Instantly share code, notes, and snippets.

@sapegin
Created December 7, 2011 12:51
Show Gist options
  • Save sapegin/1442684 to your computer and use it in GitHub Desktop.
Save sapegin/1442684 to your computer and use it in GitHub Desktop.
jQuery Tag Filter
/**
* jQuery Tag Filter
*
* @version 0.1
* @requires jQuery 1.7.1
* @author Artem Sapegin
* @copyright 2011 Artem Sapegin (sapegin.ru)
* @license http://creativecommons.org/licenses/by/3.0/
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory); // AMD. Register as an anonymous module.
} else {
factory(jQuery); // Browser globals
}
}(function ($) {
$.fn.tagFilter = function(options) {
options = $.extend({}, $.fn.tagFilter.defaults, options);
return this.each(function() {
new TagFilter($(this), options);
});
};
$.fn.tagFilter.defaults = {
barSelector: '.tags',
linkSelector: 'li',
linkActiveClass: 'active',
tagClassPrefix: 'tag_'
};
function TagFilter(container, options) {
this.container = container;
this.options = options;
this.init();
}
TagFilter.prototype = {
init: function() {
this.bar = this.container.find(this.options.barSelector);
if (!this.bar.length) return;
this.bar.delegate(this.options.linkSelector, 'click', $.proxy(this.tagClick, this));
this.tagClassRegExp = new RegExp('\\b' + this.options.tagClassPrefix + '.*?\\b', 'g');
},
tagClick: function(e) {
var link = $(e.target),
tag = link.data('tag-id');
// Replace tag class on container
this.container[0].className = this.container[0].className.replace(this.tagClassRegExp, '');
if (tag) this.container.addClass(this.options.tagClassPrefix + tag);
// Highlight button
link.siblings().removeClass(this.options.linkActiveClass);
link.addClass(this.options.linkActiveClass);
return false;
}
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment