David19801
David19801

Reputation: 11448

link press using keys in jquery

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?

Upvotes: 1

Views: 337

Answers (3)

benni_mac_b
benni_mac_b

Reputation: 8887

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()

Upvotes: 1

sinsedrix
sinsedrix

Reputation: 4775

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

Upvotes: 1

ianbarker
ianbarker

Reputation: 1254

Here is a simple method

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

Upvotes: 0

Related Questions