How to get the keyboard key value with jQuery and run a custom action

javascript-logo

This is probably the simplest way to capture the key that the user pressed and execute an action (in this case just a simple console.info).

(function() {

    function customAction() {
        console.info("You have pressed an 'a' in your keyboard");
    }

    $(window).on('keypress', function(event) {
        console.log(event.keyCode);

        // keyCode te da el código de la tecla que presiones
        if (event.keyCode === 97) { // The 'a' key was activated
            customAction();
        }
    });

})(jQuery);

That’s it, enjoy it!

Leave a Reply

Your email address will not be published. Required fields are marked *