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,793
  • 12
  • 71
  • 118
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
  • 310,957
  • 84
  • 592
  • 636
0

Untested:

$("body").keypress(function(event) {    
  if ( event.which == 13 ) { // put your own key code here    
     event.preventDefault();    
     $("#yourbutton").click();    
   }    
});
Grim...
  • 16,518
  • 7
  • 45
  • 61
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
  • 11,033
  • 4
  • 35
  • 50
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,577
  • 2
  • 39
  • 43