0

I have a lot of buttons in my web tool. I have .click() events for each of them. I am not sure how to add a keyboard shortcut along with the click so that the user can either click the button or press a key (e.g 'k') on the keyboard to call the button function.

$('#myButton').click(function () {
        // here is my code to be run when clicked
    });

how to add for example 'k' key to this button. I also want to be able to disable the click and keypress at some point. So how can I then disable both of the event listeners?

kmoser
  • 8,780
  • 3
  • 24
  • 40
Anne
  • 77
  • 8

1 Answers1

2
var myButton=document.querySelector("#myButton");
document.body.addEventListener("keydown",function(){
    var code=75; // 75 is keycode of 'k'
    if(event.keyCode==code)
    {
        myButton.click();
    }
});

Here keydown event is added to body so that when a user clicks a key (here it is k), the myButton will be 'clicked', which is it's click event handler will be executed.

To get the keyCodes visit this site keycode.info or try console logging keycodes when pressing the keys.

27px
  • 430
  • 5
  • 16