Reputation: 10880
I am using the following script to filter out divs that do not contain text in an inbox. (Similar to friends tab on Facebook)
$('#friend_search_form input').keyup(function(){
var $searchString = $(this).val();
$('.buddy').show();
$('.buddy_name > a:contains('+$searchString+')').closest('.buddy').hide();
console.log($searchString);
})
The problem is when you are typing, it takes a lot of resources and get buggy.
What is the better way to write this?
Upvotes: 0
Views: 135
Reputation: 12838
Using only a class name as a selector is way slower than for example an ID or even specifying the tag name as well as the class. You could also narrow the selector down by starting with an ID, something like this: $('#buddies div.buddy');
(immediately finds the #buddies element then only needs to match div element's class names) instead of just $('.buddy')
(which goes through every element on the page and tries to match the class name).
Upvotes: 0
Reputation: 298166
Instead of running your code every keypress, why not wait until the user stops typing for a period of time?
var typingTimeout;
$('#friend_search_form input').keyup(function(e) {
if (typingTimeout != undefined) {
clearTimeout(typingTimeout);
}
typingTimeout = setTimeout(function() {
var $searchString = $(this).val();
$('.buddy').show();
$('.buddy_name > a:contains('+$searchString+')').closest('.buddy').hide();
console.log($searchString);
}, 500);
});
Upvotes: 3