I am using javascript to create a pop-up drop-down list with a search box. It is identical to the one described at the end of this w3schools.com article: How TO - Search/Filter Dropdown
It works fine with the mouse, but I would also like to be able to use the arrow keys to go up/down the filtered list and then select the item with the Enter key.
I initially tried to capture the keydown event and then move the mouse up/down the appropriate amount, but this appears to be impossible. So I'm at a loss as to how to use the arrow keys in the filter box to change the highlight in the floating dropdown and then click the link.
I'd welcome any suggestions. Thanks.
I have found the answer to my own question (often the way).
Having realised that I cannot get JavaScript to move the mouse (not allowed), my solution is to have a global variable (called "item") holding the index number of the currently highlighted item. I then capture the arrow key presses to highlight the next item in the list up/down (remembering to un-highlight the previous item). And the Enter key activates the link for the currently highlighted item.
Here is it working in JS Fiddle
This is the JavaScript I added to the original code:
//Additional key press code starts here
document.getElementById("myInput").addEventListener("keydown", function (e) {CheckArrrow(e.keyCode);});
var item = 0; //global var holding current highlit item
function CheckArrrow(e) {
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
item_original = item;
if (e==40) { //Down arrow
item++;
while (item<a.length && a[item].style.display=="none") {
item++; //find next visible element
}
if (item>=a.length) {
item = item_original;
}
else { //unhighlight old selection, highlight new selection
a[item_original].style.backgroundColor = "";
a[item].style.backgroundColor = "#ddd";
console.log(a[item].innerText);
}
}
if (e==38) { //Up arrow
item--;
while (item>=0 && a[item].style.display=="none") {
item--; //find next visible element
}
if (item<0) {
item = item_original;
}
else { //unhighlight old selection, highlight new selection
a[item_original].style.backgroundColor = "";
a[item].style.backgroundColor = "#ddd";
console.log(a[item].innerText);
}
}
if (e==13) { //Enter key
link = a[item].href;
console.log("Going to " + link);
window.location.href = link; //go to link
}
}