Created
June 11, 2015 15:49
-
-
Save IOExceptional/0175046db44a0b01c6d6 to your computer and use it in GitHub Desktop.
A more advanced row filter with localstorage persistence
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
var addFilter; | |
(function () { | |
var filter = function (searchBox, targetClass) { | |
var value = searchBox.value; | |
var hiddenClass = targetClass + "SearchHidden"; | |
var cacheArray = JSON.parse(localStorage.getItem(hiddenClass)); | |
cacheArray = []; | |
localStorage.setItem(hiddenClass, JSON.stringify(cacheArray)); | |
localStorage.setItem(searchBox.id, value); | |
//Nothing in the box, remove <targetclass>searchhidden class | |
if (value.length < 1) { | |
filterRecalculate(hiddenClass, targetClass); | |
return; | |
} | |
var targets = $("." + targetClass); | |
for (var i = 0; i < targets.length; i++) { | |
var currentTarget = $(targets[i]); | |
var parent = currentTarget.closest(".row"); | |
var rowName = "row" + i; | |
if (!currentTarget.text().trimLeft().startsWith(value) && | |
cacheArray.indexOf(rowName) == -1) { | |
cacheArray.push(rowName); | |
} | |
} | |
localStorage.setItem(hiddenClass, JSON.stringify(cacheArray)); | |
filterRecalculate(hiddenClass, targetClass); | |
}; | |
var filterRecalculate = function (hiddenClass, targetClass) { | |
var cacheArray = JSON.parse(localStorage.getItem(hiddenClass)); | |
cacheArray = checkEmptyCache(cacheArray, hiddenClass); | |
$("." + hiddenClass).removeClass(hiddenClass); | |
var targets = $("." + targetClass); | |
for (var i = 0; i < cacheArray.length; i++) { | |
//remove "row" | |
var rowId = cacheArray[i]; | |
rowId = rowId.substring(3, rowId.length); | |
var currentTarget = $(targets[rowId]); | |
var parent = currentTarget.closest(".row"); | |
if (!currentTarget.hasClass(hiddenClass)) { | |
$(parent).addClass(hiddenClass); | |
} | |
} | |
}; | |
var checkEmptyCache = function (cacheArray, hiddenClass) { | |
if (cacheArray === undefined || cacheArray === null) { | |
cacheArray = []; | |
localStorage.setItem(hiddenClass, JSON.stringify(cacheArray)); | |
} | |
return cacheArray; | |
}; | |
addFilter = function (searchBoxId, targetClass) { | |
$(searchBoxId).on('keyup', function () { | |
filter(this, targetClass); | |
}); | |
filterRecalculate(targetClass + "SearchHidden", targetClass); | |
//remove the # from start of ids | |
var key = searchBoxId.substring(1, searchBoxId.length); | |
var text = localStorage.getItem(key); | |
$(searchBoxId).val(text); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment