Skip to content

Instantly share code, notes, and snippets.

@AJLeonardi
Created July 18, 2018 12:16
Show Gist options
  • Save AJLeonardi/17533c8ab1610b3ba33e6e14a5a96864 to your computer and use it in GitHub Desktop.
Save AJLeonardi/17533c8ab1610b3ba33e6e14a5a96864 to your computer and use it in GitHub Desktop.
a simple javascript class to enable client-side searching across a list of elements on a page.
/*
Setup:
1. Add a unique class to the "container" of the list of items you'll be searching across. The Container must be the closest parent to the elements (e.g. an unordered list)
2. Ensure that each element that will be considered for search has a unique ID
3. Add the class 'search-item' to each element that will be considered for search
4. Add the data-search-string attribute to each element that will be considered for search. This attribute should contain the text that users would search on.
5. ItemSearch assumes the search will be done through user input via an input field. Give your input field a unique ID.
Get it Working On your Page:
$(document).ready(function () {
var my_first_search_instance = new ItemSearch('unique-class-of-container', 'unique-id-of-input-box');
}
**ItemSearch is not case sensitive. If you want a case sensitive search just search for and remove '.toLowerCase()' in the code below
**Requires jQuery
JSFiddle: https://jsfiddle.net/AJLeonardi/sz0fLvpk/17/
*/
class ItemSearch{
constructor(container_class, search_input_id)
{
var instance = this;
this.item_list = instance.construct_search_list(container_class);
this.list_length = this.item_list.length;
this.search_field = document.getElementById(search_input_id);
this.search_field.addEventListener("input", function(e){
var search_string = e.target.value;
instance.search(search_string);
}, false);
}
construct_search_list(container_class){
var class_string = '.' + container_class;
var $search_elements = $(class_string).children('.search-item');
var return_list = [];
$search_elements.each(function(index){
var item_dict = {
string: $(this).data('search-string').toLowerCase(),
id: $(this).attr('id')
}
return_list.push(item_dict);
});
return return_list;
}
search(search_string){
var hide_options = {
duration:'fast',
easing:'linear',
};
search_string = search_string.toLowerCase();
for (var i = 0; i < this.list_length; i++) {
var id_string = '#' + this.item_list[i].id;
if (this.item_list[i].string.includes(search_string) === false){
$(id_string).hide(hide_options);
}
else{
$(id_string).show('fast');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment