Musa
Musa

Reputation: 315

keypress event in jQuery

I have a page with two button. When I press '5' I want that button1 to be clicked and on pressing '6' Button 2 to be clicked. Is it possible using jQuery?

Can I also handle Ctrl+5 in jQuery?

Upvotes: 2

Views: 2018

Answers (2)

Jose Basilio
Jose Basilio

Reputation: 51538

I recommend binding to the keyup event to prevent event duplicate firings. Here's some sample assuming buttons with Ids, button1 and button2.

$(function() {
    $(document).keyup(function(e) {
       if(e.keyCode == 53 || e.keyCode == 101) { //number 5
          $("#button1").trigger('click');
       } else if(e.keyCode == 54 || e.keyCode == 102) { //number 6
          $("#button2").trigger('click');
       }
   });
});

Trapping CTRL+5 is very tricky and in the case of Chrome, it is intercepted by the browser.

Upvotes: 3

Ólafur Waage
Ólafur Waage

Reputation: 70001

Check out the event helpers in jQuery. Things like keypress and others.

In the keypress demo, when you enter a key into the box, you get to know the charcode number of that key.

For example 5 is 53 and 6 is 64

Upvotes: 1

Related Questions