Created
February 22, 2012 11:29
-
-
Save afgomez/1884334 to your computer and use it in GitHub Desktop.
jQuery filterator
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
/** | |
* jQuery filterator | |
* | |
* Filter collections of elements using javascript. | |
* Uses HTML5 data attributes to get the filter values. | |
* | |
* Usage: | |
* | |
* $('element_containing_filters').filterator( { target: filter_criteria, items: selector_or_jquery_collection_to_filter } ); | |
* | |
* | |
* Example: | |
* | |
* <div id="filters"> | |
* <p>Filter by color</p> | |
* <a href="#">All</a> | |
* <a href="#" data-filter="r">Red</a> | |
* <a href="#" data-filter="g">Green</a> | |
* <a href="#" data-filter="b">blue</a> | |
* </div> | |
* | |
* <ul class="elements"> | |
* <li data-color="r">...</li> | |
* <li data-color="b">...</li> | |
* <li data-color="b">...</li> | |
* <li data-color="g">...</li> | |
* <li data-color="b">...</li> | |
* <li data-color="r">...</li> | |
* <li data-color="r">...</li> | |
* </ul> | |
* | |
* <script type="text/javascript"> | |
* $('#filters').filterator({ | |
* target: 'color', // data attribute that should be used to filter elements, | |
* items: '#elements li' // Elements. Could use a string which will be passed to jQuery or a jQuery collection. | |
* }); | |
* </script> | |
* | |
*/ | |
(function($) { | |
$.fn.filterator = function(opts) { | |
return this.each(function() { | |
// Error handling | |
if (!opts.target) { | |
throw new Error('Falta el parámetro "target"'); | |
} | |
if (!opts.items) { | |
throw new Error('Falta el parámetro "items"'); | |
} | |
// Initialize vars | |
var el = $(this), | |
target = opts.target, | |
items = (typeof(opts.items) == 'string' ? $(opts.items) : opts.items); | |
// Click handling | |
el.delegate('a', 'click', function(e) { | |
e.preventDefault(); | |
var $t = $(this); | |
if ($t.hasClass('selected')) { // Is the active link. Do nothing | |
return; | |
} | |
var filter = $t.data('filter'); | |
if (filter) { // we have filter! | |
items.hide(); | |
items.filter('[data-' + target + '=' + filter + ']').show(); | |
} else { // No filter. Show all | |
items.show(); | |
} | |
$t.siblings().removeClass('selected'); | |
$t.addClass('selected'); | |
}); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment