1

I have a HTML page with jquery loaded in and 2 links on the page.

<a href='www.example.com'>Buttona</a>
<a href='www.example2.com'>Buttonb</a>

How can I make pressing the "1" key be like pressing the first link, and pressing the "2" key be like pressing the second link using jquery?

David19801
  • 11,214
  • 25
  • 84
  • 127
  • Check this out http://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-hand – Sandeep G B Feb 02 '12 at 13:05

3 Answers3

1

Give the links an id so you can reference them so

<a href='www.example.com' id="linkA">Buttona</a>

Then on your page add the jquery to capture the key up of 1 to find linka and click.

$("html").live("keyup", function(e) {
   if(e.keyCode === 49){
      //$("#linkA").click();
      window.location.href = $('#linkA').attr('href');
   }
}

If using jquery 1.7 you can use .on() instead on .live()

benni_mac_b
  • 8,803
  • 5
  • 39
  • 59
  • It is recognizing the key code but is not going to the link. I am using 1.7.1... – David19801 Feb 02 '12 at 13:30
  • `click()` just triggers the event. It doesn´t click the element and follow the link. Use `window.location.href = $('#linkA').attr('href');` – Stefan Feb 02 '12 at 13:37
1

Wouldn't "accesskey" attribute be simpler ?

<a href='www.example.com' accesskey='0'>Buttona</a>
<a href='www.example2.com' accesskey='1'>Buttonb</a>

EDIT You may need to combine with Alt key

sinsedrix
  • 4,336
  • 4
  • 29
  • 53
0

Here is a simple method

$(window).bind('keyup',function(e) {
 if ( e.keyCode == 49 ) {
   // 1 
 }
 if ( e.keyCode == 50 ) {
   // 2 
 }
});
ianbarker
  • 1,255
  • 11
  • 22