0

I have a button in HTML and I want to provide a shortcut key to it, which should run the functionality as when button clicks what happens.

Is it possible to do something like this using JavaScript or jQuery.

isNaN1247
  • 17,513
  • 12
  • 69
  • 116
Pavan573
  • 81
  • 1
  • 1
  • 5
  • check this out http://stackoverflow.com/questions/593602/keyboard-shortcuts-with-jquery – Leigh Ciechanowski Dec 23 '11 at 11:40
  • I think you can use Hotkeys. Using hotkeys you can add functionalities like pressing Ctrl+S will submit form. I have found only this [link](https://github.com/jeresig/jquery.hotkeys) for Hotkeys – Nick Dec 23 '11 at 11:43

4 Answers4

3

You can do this using plain HTML: accesskey="x". Then you can use alt+x (depending on the browser though if it's alt or something else)

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
0

Untested:

$("body").keypress(function(event) {    
  if ( event.which == 13 ) { // put your own key code here    
     event.preventDefault();    
     $("#yourbutton").click();    
   }    
});
Grim...
  • 15,954
  • 7
  • 42
  • 60
0

It's pretty easy using jQuery. To trigger a button:

$('#my-button').trigger('click');

To monitor for keypress:

$(window).keypress(function (event) {
    if (event.which === 13) { // key codes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
        event.preventDefault();
        $('#my-button').trigger('click');
    }
});

Now, if you want to use the Ctrl key or similar you use

    if (event.which === 13 && event.ctrlKey)

and similar with event.altKey, event.shiftKey.

Nathan MacInnes
  • 10,885
  • 4
  • 34
  • 48
0
$(document).on('keypress', function (e) {
            if (e.keyCode === youreKeyCodeHere) {
            // if (e.keyCode === youreKeyCodeHere && e.shiftKey === ture) { // shift + keyCode
            // if (e.keyCode === youreKeyCodeHere && e.altKey === ture) { // alt + keyCode
            // if (e.keyCode === youreKeyCodeHere && e.ctrlKey === ture) { // ctrl + keyCode
                $('youreElement').trigger('click');
            }
        });

Where youreKeyCode can be any of the following javascript char codes , if you're shortcut needs an alt (shift, ctrl ...) use the commented if's . youreElement is the element that holds the click event you whant to fire up.

Poelinca Dorin
  • 9,341
  • 2
  • 36
  • 43