views:

1597

answers:

2

I am trying to add keyboard navigation to Menu(ul li based ) , i have bound the keydown event to menu (or should i bind keydown to the document ?)

the handler function used is given below

 KeyDown: function(e) {        

 var toFocus = false;


            if (e.keyCode == 38) {
         toFocus = $((e.target/* li */).next()[0]);
      }
                if (e.keyCode == 40) {
         toFocus = $((e.target).next()[1]);
      }
    if (toFocus) {
        $(e.target).attr('tabIndex', '-1');
        $(toFocus).attr('tabIndex', '0');
        toFocus.focus();
        return false;
  }
  }

here i get e.target as html instead of li ?

can u suggest any other way to add keyboard navigation ?

+1  A: 

I just wonder if, instead of doing this by your self, why not using an already existing plugin?

jQuery Keyboard Navigation

demo page here

my demo: just to add a demo page of an example

balexandre
I the plugin is complex , all i need is to set focus to my menu , and get the e.target to return the current menu item
ravikiran
you're kidding right? complex? mate... please look at my own example and tell me what complex is this all about! :-)
balexandre
Thanx for the demo , btw i dint mean the usage of the plugin was complex , i ment the plugin complex calculations about x y positions n stuffs , the code i mentioned above was working only problem with it was it returned html as event.target , i just need to find the current li which has the focus
ravikiran
all those lines of code you do in a cleaner manner and it's much better for future updates than look at your code ;) - with one line of code you do everything in the navigation (the init line) the rest is just animations to show you some nice effect.
balexandre
the bottom line is, why trying to re-invent the wheel? Code Reuse is what we all should do in the first place as developers.
balexandre
A: 

Try to use custom attribute to hold the tabid for up and down.

...KeyDown: function(e) {
    var Direction;
    if (e.keyCode == 38)
      Direction = "toUp";
    else Direction = "toDown";

    var Focus = $("li[tabid=\""$(e.target.id).attr(Direction)"\"]");
    Focus.focus();
}

---

<li ... tabid="1" toUp="-1" toDown= "2" />
<li ... tabid="2" toUp= "1" toDown= "3" />
<li ... tabid="3" toUp= "2" toDown= "4" />
<li ... tabid="4" toUp= "3" toDown="-1" />

The above code is just to show the idea, it is late now and I didn't have time to test it. So please don't vote me down for not working.

Hope that helps

NawaMan