Scenario
Currently filtering through a list of ~3100 rows of data presented to the end-user in the form of an index (think, list of car models).
This is done in such a way that every item is available in a long list to the end-user however they have the possibility to filter down their results into something more relevant to them.
I have gone through three variations of my filtering functionality which has greatly improved, however the fact that my jQuery skills lack experience, was wondering whether or not my implementation can be improved in the following ways:
- Readability
- Performance
var lis = $('#some-list .some-entry');
var list = $.makeArray(lis.map(function(k, v) {
return $(v).text().toLowerCase();
}));
var filterDelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#filter').keyup(function() {
var userInput = $(this).val();
filterDelay(function() {
var count = 0;
lis.each(function(index, value) {
if (list[index].indexOf(userInput) >= 0) {
count++;
$(value).show();
} else {
$(value).hide();
}
});
if (count == 1) {
$("#filter-results").text(count + " Result");
} else {
$("#filter-results").text(count + " Results");
}
}, 250);
});
The reason for the callback functionality is so that jQuery/JS does not start filtering through ~3100 rows of data every time the user presses a key. Instead, we want to wait for 250ms and then fall back to our filtering functionality afterwards.
This greatly helps the user-experience and is overall less stressing on the browser.
Question
My previous examples used toggle(bool)
rather than show()
or hide()
to add or remove a row from the list (when filtered). Are there any inherent differences in terms of performance between the two?
Additionally, I am looking to implement a loading animation when:
- The user is typing
- The filter has starting filtering
And the removing it when the filtering is complete. Thus, would it make sense to toggle the loading animation, or add/remove it from the DOM respectively?
Toggle it off would mean that the animation is still occurring in the background regardless whether or not any filtering is being made. Adding it or removing to the DOM however will have its own performance drop.
What would one recommend? I don't want to make it seem like it's for micro-optimization purposes but simply looking to implement my filter functionality in a neater way for possible future re-use.
Update(s)
Added load animations by combining Bootstrap and jQuery like so:
$('#filter').keyup(function() { //... $('#filter-icon-load').removeClass('hidden'); //... $('#filter-icon-load').addClass('hidden'); //... });