Have following listener for keyboard ArrowDown event(it’s key code is 40):
window.onload = function() {
var itemsContainer = document.getElementById('cities-drop');
document.addEventListener('keyup',function(event){
if (event.keyCode == 40 && itemsContainer.style.display=='block') {
event.preventDefault();
for (var i=0;i<itemsContainer.children.length-1;i++){
if (itemsContainer.getAttribute('class').substr('hovered')!=-1){
itemsContainer.children[i].setAttribute('class','');
itemsContainer.children[i].nextSibling.setAttribute('class','hovered');
//break;
}
}
}
});
in this case hovering jumps to last element in list, after ArrowDown pressed.
In case break is uncommented,it jumps to the second element and doesn’t jumping any more.
Can’t get the principle,how to do, that listener always listens…
EDIT
live demo
perhaps,it’s a matter of closure,but i’m not certain
After looking at your code and realizing what you’re trying to do, I think your error is using
substrwhere you should be usingindexOf. Here is the updated line:More detail:
What you were actually doing was using a
substrwith a string value for thestartindex. Not sure what the result of that would be, but apparently it’s not -1, since the conditional was returning true every time, causing the next element to be hovered EVERY time, all the way down to the bottom of the list. With thebreakstatement in there, it was executing the if-statement at the first element (causing the second element to be ‘hovered’), and then quitting.I would leave the
breakstatement in there after correcting your code, so that the loop stops after it finds its match, and doesn’t loop through the rest of the items unnecessarily.EDIT:
I found a couple other issues in your code as well. Here is an example that works for me in IE and FF, at least (haven’t tested in Safari, Opera or Chrome):
Detail: For me, in IE9, the function was never being called. Instead, I just made it a regular function and added an
onkeydownevent to thebodytag.Next, for cross-browser compatibility, you should check to make sure that
event.preventDefaultexists before using it. I was getting a JS error in IE.In your if-statement, you had
itemsContainer.getAttribute('class'). Firstly, you needed to useitemsContainer.children[i]. Secondly,.getAttribute('class')didn’t work for me in IE, so I switched it to just.className.Lastly,
itemsContainer.children[i].nextSiblingdidn’t work for me, but it’s simple enough to just change it toitemsContainer.children[i+1]to get the next sibling.