Need help optimizing a filter that's powered by jquery...
I have a page with a very large table. On this page is a text box that users can type in letters or words to filter the table. If they type 'abo' for example, only rows that contain 'abo' will remain visible, all other rows will be hidden. This is done by adding a class "visible" to all tr elements, and removing the "visible" class from elements that do not contain what the user entered. This works great for small tables, but when my tables get to be 1,000 rows and up, it becomes very slow. Any help speeding this up is greatly appreciated.
Here is my code:
- function initFilter() {
//inits the results filter
//needs to be called everytime XML is parsed/displayed in table
//$('tbody tr').addClass('visible'); //moved this to be added when table is generated serverside.
$('#filter').keyup(function(event) {
expr = "typingStopped("+event.keyCode+")";
if (undefined===window.typingTimer)
{
typingTimer = setTimeout(expr, 300);
}
else
{
clearTimeout(typingTimer);
typingTimer = setTimeout(expr, 300);
}
});
}
- function typingStopped(event) {
//keyCode 27 = esc key. If filter textbox is empty, show all rows.
//Have to add visible class back to every row, or filter will show only blank rows.
if (event.keyCode == 27 || $('#filter').val() == '')
{
$('#filter').val('');
$('tbody tr').removeClass('visible').show().addClass('visible');
}
//if there is text in filter textbox, apply filter
else
{
filter('tbody tr', $('#filter').val());
}
}
function filter(selector, query) {
query = $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex query
$(selector).each(function() {
($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
});
}