RanSch
RanSch

Reputation: 469

adding keyboard navigation with jquery

I built a complex jquery-html game and I used the click event many times. In order to make it accessible I need to make the keyboard navigation...Is there any jquery plugin or any way to make all the click events work with the enter key too? For example:

<!DOCTYPE html>
<html>
 <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
  </script>
  <script>
  $(document).ready(function(){
    $("p").click(function(){
      $(this).hide();
    });
  });
  </script>
  <style>p:focus {
  outline: 1px solid grey;
  }</style>
 </head>
 <body>
  <p tabindex="1">Par1</p>
  <p tabindex="2">Par2</p>
 </body>
</html>

If I press enter when a paragraph is focused, so nothing happens...I thought to create keyboard event and detect the enter key, but it would be very tedious...Any solution?

Upvotes: 0

Views: 1917

Answers (3)

tobib
tobib

Reputation: 2406

From Document Object Model (DOM) Level 3 Events Specification

In addition to being associated with pointer devices, the click event type must be dispatched as part of an element activation

This means that a click event will be fired for example if a link is activated. So you could replace the <p tabindex="1">…</p> by <a href="#" tabindex="1">…</a> and prevent the default action. Of course this is not necessarily simpler than any of the other proposals.

Upvotes: 1

Jirkaz
Jirkaz

Reputation: 19

You can use virtual focus with adding class. Can be applied to any event (mouse or keyboard).

A little inspiration how it might work

$( "#target" ).keydown(function( event ) {
  switch(event.which) 
  {
    case 37 : //Arrow left
              break;
    case 39 : //Arrow left
              break;
    case 38 : //Arrow up
              break;
    case 40 : //Arrow down
              break;
    case 13 : //Enter
              break;
    // next keys....

  }
});

http://jsfiddle.net/jirkaz/HA4m3/

Moving active class with keyboard (arrows) and get text in active div with key Enter.

Upvotes: 0

sdespont
sdespont

Reputation: 14025

You need to catch the key events with http://api.jquery.com/keydown/ like this

$( "#target" ).keydown(function( event ) {
  switch(event.which) 
  {
    case 37 : //Arrow left
              break;
    case 39 : //Arrow left
              break;
    case 38 : //Arrow up
              break;
    case 40 : //Arrow down
              break;
  }
});

Upvotes: 4

Related Questions