This post will discuss creating keyboard shortcuts with JavaScript, third-party libraries like jQuery, hotkeys, and mousetrap.

The idea is to listen to the keypress, keydown, or keyup JavaScript events and define the keyboard shortcut logic in the callback. To read the value of the key pressed by the user, you can use one or more properties defined in KeyboardEvent object like altKey, ctrlKey, shiftKey, code, key, etc.

1. Pure JavaScript

In plain JavaScript, you can use the addEventListener() method to listen for keydown event. The following example implements shortcut for Alt+x keyboard event using KeyboardEvent.altKey and KeyboardEvent.code property.

JS


HTML



Edit in JSFiddle

 
Here’s an example using the KeyboardEvent.key attribute.

JS


HTML



Edit in JSFiddle

2. Using jQuery

With jQuery, you can use the event.which property to watch for the keyboard key input.

jQuery


HTML



Edit in JSFiddle

3. Using hotkeys.js

There are several third-party keyboard libraries available to create keyboard shortcuts in JavaScript. One such popular library is hotkeys. You can use it like:

JS


HTML



Edit in JSFiddle

4. Using mousetrap.js

Mousetrap is another good JavaScript library for handling keyboard shortcuts in JavaScript. It can be used as follows:

JS


HTML



Edit in JSFiddle

That’s all about creating keyboard shortcuts in JavaScript and jQuery.