Skip to content

Commit

Permalink
Listbox Examples: Add typeahead functionality (pull #481)
Browse files Browse the repository at this point in the history
For issue #123, add typeahead in the lists so that typing the first letters of the name of an option moves focus to the next option that starts with those letters.
  • Loading branch information
mcking65 authored Oct 17, 2017
2 parents 392bf80 + 531f2ee commit c98a878
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
3 changes: 0 additions & 3 deletions examples/listbox/js/listbox-rearrangeable.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,4 @@ window.addEventListener('load', function () {

ex2ImportantListbox.setupDelete(document.getElementById('ex2-add'), ex2UnimportantListbox);
ex2UnimportantListbox.setupDelete(document.getElementById('ex2-delete'), ex2ImportantListbox);

var ex3 = document.getElementById('ex3');
var ex3Listbox = new aria.Listbox(document.getElementById('ss_elem_list'));
});
60 changes: 60 additions & 0 deletions examples/listbox/js/listbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ aria.Listbox = function (listboxNode) {
this.upButton = null;
this.downButton = null;
this.deleteButton = null;
this.keysSoFar = '';

this.registerEvents();
};
Expand Down Expand Up @@ -149,7 +150,66 @@ aria.Listbox.prototype.checkKeyPress = function (evt) {
this.focusItem(nextItem);
}
break;
default:
var itemToFocus = this.findItemToFocus(key);
if (itemToFocus) {
this.focusItem(itemToFocus);
}
break;
}
};

aria.Listbox.prototype.findItemToFocus = function (key) {
var itemList = this.listboxNode.querySelectorAll('[role="option"]');
var character = String.fromCharCode(key);

if (!this.keysSoFar) {
for (var i = 0; i < itemList.length; i++) {
if (itemList[i].getAttribute('id') == this.activeDescendant) {
this.searchIndex = i;
}
}
}
this.keysSoFar += character;
this.clearKeysSoFarAfterDelay();

var nextMatch = this.findMatchInRange(
itemList,
this.searchIndex + 1,
itemList.length
);
if (!nextMatch) {
nextMatch = this.findMatchInRange(
itemList,
0,
this.searchIndex
);
}

return nextMatch || itemList[this.searchIndex];
};

aria.Listbox.prototype.clearKeysSoFarAfterDelay = function () {
if (this.keyClear) {
clearTimeout(this.keyClear);
this.keyClear = null;
}
this.keyClear = setTimeout((function () {
this.keysSoFar = '';
this.keyClear = null;
}).bind(this), 500);
};

aria.Listbox.prototype.findMatchInRange = function (list, startIndex, endIndex) {
// Find the first item starting with the keysSoFar substring, searching in
// the specified range of items
for (var n = startIndex; n < endIndex; n++) {
var label = list[n].innerText;
if (label && label.toUpperCase().indexOf(this.keysSoFar) === 0) {
return list[n];
}
}
return null;
};

/**
Expand Down

0 comments on commit c98a878

Please sign in to comment.