keyboard navigation using knockout

1.2k views Asked by At

I have an observable array in my viewmodel which I am binding to a list of div elements using foreach and template binding. How can I navigate through these div elements using keyboard's up and down arrow key.

The way I want is when the user clicks on 1 of the div element that gets the focus and when he presses the down arrow key the next div element gets focus and similarly when he presses the up arrow key the previous div gets focus. I have searched all over the internet but didn't came across a suitable answer. Thanks!!

2

There are 2 answers

0
beauXjames On

There are a few ways I would imagine doing this...here's one...

Give a 'selectedObject' property to your viewModel and handle the click event per div via knockout. When the event is triggered, you can set the 'selectedObject' to the context passed over. In this click event, $.toggle() the css class via jQuery and set up a handler for the down-arrow event on the new div element (be sure to clear out existing event handlers so not to conflict with the new one).

Click-Binding in knockout: http://knockoutjs.com/documentation/click-binding.html Event Binding in JQuery : http://api.jquery.com/bind/

Provide a fiddle with your attempts of this and I'll try to follow-up.

0
Ryan Leach On

I'd advise handling the keyboard shortcuts in the topmost container of your "component/template" for this particular widget. this lets you handle the up / down in one place, instead of making each li responsible for it's shortcuts.

Additionally in order to make the elements selectable using the mouse and native tab events, look into "roving tab indices".

Looking into the focus binding for knockout helps too.

Edit: found this helpful library as well. https://github.com/bramstein/knockout.selection