Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom selector and fix for change event #18

Merged
merged 4 commits into from
Nov 3, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Available options:

- timeout: How many milliseconds to wait after keydown before filtering the list. Default is 0.
- callback: A callback method which will be given the number of items left in the list.
- selector: By default, the plugin will match the filter against the text of the `li`. If specifed, the selector will be applied to the `li` and the resulting text will be used instead. **WARNING:** Use of complex selectors may reduce performance significantly, especially in large lists!

Example:

Expand Down
18 changes: 12 additions & 6 deletions jquery.fastLiveFilter.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ jQuery.fn.fastLiveFilter = function(list, options) {
options = options || {};
list = jQuery(list);
var input = this;
var lastFilter = '';
var timeout = options.timeout || 0;
var callback = options.callback || function() {};

Expand All @@ -27,11 +28,15 @@ jQuery.fn.fastLiveFilter = function(list, options) {
input.change(function() {
// var startTime = new Date().getTime();
var filter = input.val().toLowerCase();
var li;
var li, innerText;
var numShown = 0;
for (var i = 0; i < len; i++) {
li = lis[i];
if ((li.textContent || li.innerText || "").toLowerCase().indexOf(filter) >= 0) {
innerText = !options.selector ?
(li.textContent || li.innerText || "") :
$(li).find(options.selector).text();

if (innerText.toLowerCase().indexOf(filter) >= 0) {
if (li.style.display == "none") {
li.style.display = oldDisplay;
}
Expand All @@ -47,11 +52,12 @@ jQuery.fn.fastLiveFilter = function(list, options) {
// console.log('Search for ' + filter + ' took: ' + (endTime - startTime) + ' (' + numShown + ' results)');
return false;
}).keydown(function() {
// TODO: one point of improvement could be in here: currently the change event is
// invoked even if a change does not occur (e.g. by pressing a modifier key or
// something)
clearTimeout(keyTimeout);
keyTimeout = setTimeout(function() { input.change(); }, timeout);
keyTimeout = setTimeout(function() {
if( input.val() === lastFilter ) return;
lastFilter = input.val();
input.change();
}, timeout);
});
return this; // maintain jQuery chainability
}