views:

196

answers:

2

I'm enabling keyboard navigation for a menu. I'm running into an issue in a particular situation:

<ul>
    <li><a href="" class="link1">link</a></li>
    <li><a href="" class="link2">link</a></li>
    <li><a href="" class="link3">link</a></li>
</ul>

the jQuery:

$('ul').keypress(function (eh){
    var keyPressed = eh.keyCode;
    if (keyPressed=='37'){
        $currentFocusedLink.closest('li').prev('li:first').find('a:first').focus()

};

What happens:

I'm capturing the arrow keys to navigate between the menus. This works EXCEPT when the cursor is before the first character of one link and I hit the back arrow.

What I think happens is that the cursor moves and then the keypress is captured. Because the cursor moves into the previous anchor tag, it then triggers focus. But because I'm also capturing the keypress and assigning focus, whatever my focus event is gets called twice.

Any way to get around this issue?

UPDATE:

Here's a bit of sample code to try out to get a good idea of what is happening.

HTML:

<div class="testNav">
      <a href="">TEST LINK 1</a>
      <a href="">TEST LINK 2</a>
      <a href="">TEST LINK 3</a>
      <a href="">TEST LINK 4</a>
      <a href="">TEST LINK 5</a>
</div>

jQUery:

var $activeLink;

$('.testNav')
    .find('a')
        .focus(function(){
             $activeLink = $(this);      
        })
        .end()
    .keypress(function (eh){
        var keyPressed = eh.keyCode;
        if (keyPressed=='37'){
            $activeLink.prev('a').focus()
        };
     });

Note that you can tab forward and backward to each link just fine.

Now, tab to the 5th link and push the back arrow. It will jump to LINK 3. Push it again and it goes to LINK 1.

I think the reason is as stated above...my script applies focus, but so does the act of moving the cursor into the previous anchor tag. Both happen when you hit the back arrow.

A: 

You could use the jCaret plugin to check if your cursor was before the first character and handle that situation as an edge case.

Alex Sexton
A: 

SOLUTION:

This should have occurred to me sooner, but the eventual fix was to attach 'preventDefault()' to the keypress event. The key is to first detect the key presses, then only preventDefault on the particular keys you are looking for (or else lose keyboard functionality on the web page).

DA