Pavan573
Pavan573

Reputation: 81

run functionality of a button

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.

Upvotes: 0

Views: 85

Answers (4)

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

$(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.

Upvotes: 0

Nathan
Nathan

Reputation: 11159

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.

Upvotes: 0

Grim...
Grim...

Reputation: 16953

Untested:

$("body").keypress(function(event) {    
  if ( event.which == 13 ) { // put your own key code here    
     event.preventDefault();    
     $("#yourbutton").click();    
   }    
});

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318578

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)

Upvotes: 3

Related Questions