Skip to content

Instantly share code, notes, and snippets.

@sikofitt
Created July 27, 2017 16:25
Show Gist options
  • Save sikofitt/5947992df85493adc766a66746c4fd42 to your computer and use it in GitHub Desktop.
Save sikofitt/5947992df85493adc766a66746c4fd42 to your computer and use it in GitHub Desktop.
On the fly search that hides divs that don't match.
searchPage = function(searchElem, divClass, hiddenClass) {
jQuery(divClass).removeClass(hiddenClass);
var search = document.getElementById(searchElem);
var needle = search.value;
needle = needle.toLowerCase();
var searchStrings = needle.split(/\W/);
for (var i = 0, len = searchStrings.length; i < len; i++) {
var currentSearch = searchStrings[i].toLowerCase();
if (currentSearch !== "") {
nameDivs = document.getElementsByClassName(divClass);
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toLowerCase().indexOf(currentSearch) === -1) {
nameDivs[j].classList.add(hiddenClass);
}
}
} else {
nameDivs = document.getElementsByClassName(divClass);
for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
nameDivs[j].classList.remove(hiddenClass);
}
}
}
}
};
// with UIkit for example.
jQuery('#search').on('keypress', searchPage('search', 'uk-card', 'uk-hidden');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment