Yasitha Srimal
Yasitha Srimal

Reputation: 11

How to press keyboard shortcuts on button click of web app using javascript/jquery/php

I am learning php and java script. I want to use keyboard shortcuts for button click of my web app. So i need to create, press keyboard shortcuts on button click of my web app using php/java script/jquery. and i am not finding a proper way to do it. what is the best way to press keyboard keys?? please help me out with this.

Upvotes: 1

Views: 593

Answers (1)

Ernesto Stifano
Ernesto Stifano

Reputation: 3130

First, we need to attach an event listener to the area where we want to capture keyboard input (use window if you want to capture everything).

Then, in the event handler, we can do whatever we want depending on the key that has been pressed. HERE you will find a chart with all key values:

let captureArea = document.getElementById('captureArea');

captureArea.addEventListener('keypress', inputHandler);

function inputHandler(e) {

    // PRINT PRESSED KEY VALUE
    console.log(e.which);

    // HANDLING EXAMPLE
    if (e.which <= 31 || (e.which >= 48 && e.which <= 57)) {
        // A NUMBER HAS BEEN PRESSED
        // SWITCH TO CORRESPONDING SLIDE
    } else if (e.which === 13) {
        // ENTER KEY HAS BEEN PRESSED
        // TRIGGER SUBMIT BUTTON HANDLER
    }

}

Obviously, this is a simple example. Depending on your intended cross-browser support, you may want to use e.which, addEventListener/removeEventListener and let legacy alternatives.

Remember to detach the event listener when not needed:

captureArea.removeEventListener('keypress', inputHandler);

And being more specific with captureArea can also help improving performance.

NOTE: I think that the question description is unclear, could be interpreted as the opposite: 'How to dispatch keyboard input events on a button click', instead of: 'How to trigger a button click based on keyboard input'. But it would have no sense to get user intentions through an event and translate it to another event type to successively re-capture it. So I prefer the second interpretation.

Upvotes: 1

Related Questions