Skip to content

Instantly share code, notes, and snippets.

@kikobr
Last active August 29, 2015 14:03
Show Gist options
  • Save kikobr/44451dd9511625ddb51b to your computer and use it in GitHub Desktop.
Save kikobr/44451dd9511625ddb51b to your computer and use it in GitHub Desktop.
filterGun - filtering dynamic content easily
<input type="text" class=".search-input">
<ul class="to-search">
<li>Apples</li>
<li>Penguins</li>
<li>Turtles</li>
</ul>
<script type="text/javascript">
$(function(){
$('.search-input').filterGun({
event: "keyup",
target: "ul.to-search li",
searchItemSuccess: function(searchedItem){
searchedItem.fadeIn(250);
},
searchItemFailure: function(searchedItem){
searchedItem.fadeOut(250);
},
searchEnd: function(count){ console.log('Success on '+count) },
});
});
</script>
(function($){
/*
$('.search-input').filterGun({
event: "keyup",
target: "ul.to-search li",
targetExtraValidation: function(searchedItem){
if( searchedItem.attr('disabled') ){ return false; }
else { return true; }
},
searchItemSuccess: function(searchedItem){
searchedItem.fadeIn(250);
},
searchItemFailure: function(searchedItem){
searchedItem.fadeOut(250);
},
searchEnd: function(count){ console.log('Success on '+count) },
});
*/
$.fn.filterGun = function(options){
var _this = this,
searchObject = $(this),
searchEvent = options.event || "keyup",
searchTarget = options.target || "ul:first-of-type li",
searchItemExtraValidation = options.targetExtraValidation || function(){ return true; },
searchItemFailure = options.searchItemFailure || function(obj){},
searchItemSuccess = options.searchItemSuccess || function(obj){},
searchEnd = options.searchEnd || function(count) {};
// When the search input object emits the specified event, it
// loops through the target items to find out which ones will filter.
searchObject.on(searchEvent, function(){
_this.filter();
});
this.filter = function(){
var searchQuery = searchObject.val(),
count = 0;
// If the actual target in the loop filters, call a success function
// otherwise, calls an error function
$(searchTarget).each(function(){
if(
$(this).val() && $(this).val().search(new RegExp(searchQuery, "i")) < 0 ||
$(this).text() && $(this).text().search(new RegExp(searchQuery, "i")) < 0
){ searchItemFailure($(this)); }
else {
// Check if it needs aditional validation before setting as filtered
if( searchItemExtraValidation( $(this) ) ){
count++;
searchItemSuccess($(this));
} else {
searchItemFailure($(this)); }
}
});
// calls and end filtering function
searchEnd(count);
}
return this;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment