By looking at your code and understanding what you are trying to do, I think your error is using substr
, where you should use indexOf
. Here is the updated line:
if (itemsContainer.getAttribute('class').indexOf('hovered') != -1)
More: In fact, you used
substr
with a string value for the
start
index. I'm not sure what the result of this would be, but apparently it is not -1, since the condition returned true every time, making the next element depend EVERY time, down to the bottom of the list. Using the
break
statement, the if statement was executed on the first element (causing the second element to hang), and then completed.
I would leave the break
statement there after correcting your code, so that the loop will stop after it finds a match, and will not overly go through the rest of the elements.
EDIT:I found a couple more problems in the code. Here is an example that works for me in IE and FF, at least (not tested in Safari, Opera or Chrome):
<html> <head> <style type="text/css"> .hovered { color:red; } </style> <script type="text/JavaScript"> function move(event) { var itemsContainer = document.getElementById('cities-drop'); if (event.keyCode == 40 && itemsContainer.style.display == 'block') { if (event.preventDefault) event.preventDefault(); if (event.cancelBubble) event.cancelBubble(); if (event.stopImmediatePropagation) event.stopImmediatePropagation(); for (var i=0; i<itemsContainer.children.length-1; i++) { if (itemsContainer.children[i].className.indexOf('hovered') != -1) { itemsContainer.children[i].className = ""; itemsContainer.children[i+1].className = "hovered"; break; } } } }; </script> </head> <body onkeydown="move(event)"> <div id="cities-drop" style="display:block;"> <p class="hovered">Item 1</p> <p>Item 2</p> <p>Item 3</p> <p>Item 4</p> <p>Item 5</p> <p>Item 6</p> <p>Item 7</p> </div> </body> </html>
Details: For me, in IE9, the function was never called. Instead, I just made it a regular function and added the
onkeydown
event to the
body
tag.
Next, for compatibility with multiple browsers, you must ensure that event.preventDefault
exists before using it. I was getting JS error in IE.
In your if-statement you have itemsContainer.getAttribute('class')
. First, you need to use itemsContainer.children[i]
. Secondly, .getAttribute('class')
did not work for me in IE, so I switched it only to .className
.
Finally, itemsContainer.children[i].nextSibling
did not work for me, but it is simple enough to just change it to itemsContainer.children[i+1]
to get the next brother.