I have a dropdown that contains around 100,000 rows which make up a list.
<input id="search" type="text" />
<ul>
<li>item 1</li>
<li>item 2</li>
...
<li>item 100,000</li>
</ul>
I have a text box which acts as a search, so as you type it matches the input to items in the list, removing what does not match. This is the class I wrote to perform the removing of list elements.
See the fiddle (list has about 2000 items)
// requires jQuery
var Search = (function(){
var cls = function (name) {
var self = this;
self.elem = $('#' + name);
self.list = $('#' + name).next('ul').children();
self.elem.bind('keyup', function () { self.change(); });
};
cls.prototype = {
change: function () {
var self = this;
// gets the closest ul list
var typed = self.elem.val();
// only do something if there is something typed
if (typed !== '') {
// remove irrelevent items from the list
self.list.each(function () {
var item = $(this).html();
if (item.indexOf(typed) === -1) {
$(this).addClass('zero');
// tried using a class with visibility hidden
} else {
$(this).removeClass('zero');
}
});
} else {
// check what list items are 'hidden' and unhide them
self.list.each(function () {
if ($(this).hasClass('zero')) {
$(this).removeClass('zero');
}
});
}
}
};
return cls;
}());
I am just adding a class which adds a height of 0, and no margin,padding, etc, but I have also tried using visibility:hidden. I have also tried using the detach method in jQuery but this is about the same in terms of speed.
Are their any JavaScript experts who can see any problems with the code, or offer some optimization techniques?
This can be done “relatively well” (in a desktop browser anyway), even with a large number of items – although the actual performance will vary based upon other factors.
The “trick” to keeping the UI responsive is to handle the searching/filtering over time via
setTimeoutorsetIntervalthat only “do so much work at a time”. I found that, at least in IE7/8 a work/rest of 20ms/30ms worked well for when I used such in a Sidebar Gadget. YMMV.If the DOM can be avoided for searching entirely (e.g. using a cache to re-create the n-items on-the-fly from an array or other searchable structure), then this might payout as well – run some benchmarks! – and keep the searching simpler.
Of course, utilizing server-side solutions (e.g. AJAX), at least for “coarse grained results”, may also be more appropriate depending upon use-case ..