I'm trying to create an html & jQuery menu that uses arrow keys for navigation and the enter button to "click" the link in said menu.
I have created a fiddle and the menu is live on the homepage of my website but here is the menu HTML:
<ul id="home_menu">
<li class="arrow-link"><a href="/blog/">Blog</a></li>
<li><a href="/resume/">Resume</a></li>
<li><a href="/portfolio/">Portfolio</a></li>
<li><a href="/tools">Tutorials</a></li>
<li><a href="/contact/">Contact</a></li>
</ul>
And here is the .arrow-link
class:
.arrow-link{
background: url(media/images/selectArrow.png) no-repeat;
background-position: 0 3px;
}
If you view the console you can see I'm recording two variables, the Position Counter which indicates the <li>
element that the .arrow-link
class gets applied to (see script below), and Keystroke Value, which is pretty self explanatory.
I have created a script that is pretty simple and that just toggles the .arrow-link
class depending on the Position Counter value:
var pos = 1;
jQuery(document).keydown(function (e) {
switch (e.which) {
case 38: // up
pos--;
if (pos > 5) {
pos = 1;
} else if (pos < 1) {
pos = 5;
}
moveArrow(pos, e.which);
break;
case 40: // down
pos++;
if (pos > 5) {
pos = 1;
} else if (pos < 1) {
pos = 5;
}
moveArrow(pos, e.which);
break;
case 13: // enter
console.log("Keystroke Value: " + e.which + " (Enter)");
jQuery('.arrow-link a').trigger("click");
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
function moveArrow(pos, e) {
console.log("Position counter: " + pos);
console.log("Keystroke Value: " + e);
jQuery("#home_menu").children().removeClass("arrow-link");
jQuery("#home_menu li:nth-child(" + pos + ")").addClass("arrow-link");
}
So from this script I know that the value being passed to the case statement is correct, and I can generate output to the console upon pressing the enter button, but, on the line where I try to simulate a click (jQuery('.arrow-link a').trigger("click");
), nothing happens. I don't see any errors in the console, it just doesn't do anything.
I have also tried to use (".arrow-link a").click();
instead of jQuery('.arrow-link a').trigger("click");
but again, no dice.
What do I need to use there to take the user to the corresponding link?