Placed in: Home arrow Programming arrow Webdesign arrow Advanced keypress navigation with jQuery comprar viagra en espaƱa
comprar viagra online
comprar viagra generico barato
comprar cialis generico online
comprar cialis online seguro
Advanced keypress navigation with jQuery

A while ago, an article called "A fancy search suggestion" was placed here. Many people loved it and already used the search suggestion in their latest web project.

Still, readers gave some criticism about the script. According to Jape, Simon and others the script was missing one vital element which the Apple search does have: keypress navigation (keyboard accessibility). For that reason, I'm presenting you a way you can improve that script yourself using advanced keypress navigation with jQuery.

Advanced Keypress Navigation

Check out the demo so you can try it yourself: There is a simple menu displayed which reacts to the Up and Down arrows, as well as Enter (or Return) to follow the link.

Demo Advanced keypress navigation   Download Advanced keypress navigation

The script is (a bit) advanced because of the extra functionality when the user combines the mouse hover and keypresses. Want to know how to create it yourself? Check out the source code or follow these steps in this tutorial.


The HTML that I came up with isn't that hard to understand: Simply a division with an ID, containing an unorderd list with links.

<div id="menu">
      <li><a href=""></a></li>
      <li><a href="">Marcofolio RSS feed</a></li>
      <!-- more items could be added -->

The only thing we need to remember here is the menu-ID that we're going to use later.


I'm not going to add very many CSS details to this tutorial. All CSS stuff is pretty basic, no fancy-stuff going on. However, there is one CSS class that you should remember:

.itemhover { background-color:#b7b7b7 !important; color:#232323 !important; }

The itemhover class is added to highlight the selected item from the menu. The background-color and color are set to !important to make sure that color is displayed.


Now it's time to get our hand dirty and get down to the coding part with jQuery. First things first; We'll need to store the current selected item from the menu, including the URL where that menu item links to. So, we'll declare two variables at the top of the script:

var currentSelection = 0;
var currentUrl = '';

After loading jQuery from Google, we'll need to add a keylistener to the whole page. I've added comments to the script to make it clear.

google.load("jquery", "1.3.1");
   // Register keypress events on the whole document
   $(document).keypress(function(e) {
      switch(e.keyCode) { 
         // User pressed "up" arrow
         case 38:
         // User pressed "down" arrow
         case 40:
         // User pressed "enter"
         case 13:
            if(currentUrl != '') {
               window.location = currentUrl;

As you can see, this part requests the keyCode whenever the user hits any key on the keyboard. When the user hits "Enter (or Return)", the script checks if the currentUrl has been loaded with an URL. If so, the location of the window follows that URL.

Both the Up and Down arrow call a (non-existing) function called navigate with one parameter: The direction. Let's see what we should do inside that function.

function navigate(direction) {
   // Check if any of the menu items is selected
   if($("#menu ul li .itemhover").size() == 0) {
      currentSelection = -1;
   if(direction == 'up' && currentSelection != -1) {
      if(currentSelection != 0) {
   } else if (direction == 'down') {
      if(currentSelection != $("#menu ul li").size() -1) {

The function first checks if there already is a list item with the class itemhover. If there isn't any, the currentSelection is set to -1 (0 is the first list item).

On the first go, the user can only use the Down arrow (Up arrow doesn't have any use at this point). If the Down arrow is used, it first checks if the current selected item isn't already at the bottom of the list (by checking the size). If it isn't, the currentSelection is raised by 1.

Almost the same counts for the Up arrow. When pressed, it first checks if it isn't at the top of the list (index: 0).

The end of the function calls another function called setSelected. It expects one parameter: The index of the currently selected item. This function is very small, but does a lot.

function setSelected(menuitem) {
   $("#menu ul li a").removeClass("itemhover");
   $("#menu ul li a").eq(menuitem).addClass("itemhover");
   currentUrl = $("#menu ul li a").eq(menuitem).attr("href");

The first line removes all classes inside the list called itemhover. The second line adds the class to the selected menuitem (the parameter from this function). This is the class that we created in the CSS part above, remember? The last line sets the currentUrl parameter by retrieving the href from the selected menu item. By setting the currentUrl, the Enter (or Return) keypress now works too!

Now we already have a wonderful menu that reacts to the keypresses from the user (Up, Down and Enter). But what about the mouse movements?

Mouse movements

We could do this the easy way by adding a :hover to the CSS file. This way, when the user hovers an item, it gets highlighted. But what will happen if the user combines the two? When hovering the third item with the mouse and pressing on the Down key, it would highlight the first item.

To make this also work perfectly with the mouse, we'll enhance the script with some more stuff. First, we'll need to let the menu item "know" at what index there are positioned. This is really simple to achieve, but essential to make this work. When the user hovers the third item, there is no way the item itself would know it is the third. But by adding data, it does:

// Add data to let the hover know which index they have
for(var i = 0; i < $("#menu ul li a").size(); i++) {
   $("#menu ul li a").eq(i).data("number", i);

As you can see, this part loops through all the menu items and adds the index of that item (called number) to the item itself. We'll need that data when hovering with the mouse.

So, let's add a hover-listener to the menu:

// Simulate the "hover" effect with the mouse
$("#menu ul li a").hover(
   function () {
      currentSelection = $(this).data("number");
   }, function() {
      $("#menu ul li a").removeClass("itemhover");
      currentUrl = '';

The first parameter from hover is a function when hovering the menu item. Once again, the currentSelection is set by retrieving the number that we just placed inside the data. This way, the script "knows" which item needs to be highlighted and can use the arrow keys after selecting an item with the mouse!

The second function (on mouse leave) isn't that spectacular: It removes all itemhover classes from the menu and clears the currentUrl.

Conclusion and Download

That's about it! The whole script can be viewed when downloading the source files and you can test it on the demo page. These kind of techniques can really improve the user friendliness of your website.

Demo Advanced keypress navigation   Download Advanced keypress navigation

Of course, scripts can always be improved. What do you want to see differently or do you see any bug fixes? If you're going to use this somewhere on your next project, please share!

Tags:  keypress navigation jquery webdevelopment

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
< Prev   Next >