Create keyboard shortcuts with JavaScript, jQuery, hotkeys & mousetrap library
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
|
1 2 3 4 5 6 7 |
document.addEventListener("keydown", function(event) { if (event.altKey && event.code === "KeyX") { alert('Alt + X pressed!'); event.preventDefault(); } }); |
HTML
|
1 2 3 |
<p> Press Alt + X </p> |
Here’s an example using the KeyboardEvent.key attribute.
JS
|
1 2 3 4 5 6 7 |
document.addEventListener("keydown", function(event) { if (event.altKey && (event.key === 'x' || event.key === 'X')) { alert('Alt + X pressed!'); event.preventDefault(); } }); |
HTML
|
1 2 3 |
<p> Press Alt + X </p> |
2. Using jQuery
With jQuery, you can use the event.which property to watch for the keyboard key input.
jQuery
|
1 2 3 4 5 6 7 |
$(document).keydown(function(event) { if (event.altKey && event.which === 88) { alert('Alt + X pressed!'); e.preventDefault(); } }); |
HTML
|
1 2 3 |
<p> Press Alt + X </p> |
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
|
1 2 3 4 |
hotkeys('alt+x', function(event, handler) { alert('Alt + X pressed!'); event.preventDefault(); }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <script src="https://unpkg.com/hotkeys-js/dist/hotkeys.min.js"></script> </head> <body> Press Alt + X </body> </html> |
4. Using mousetrap.js
Mousetrap is another good JavaScript library for handling keyboard shortcuts in JavaScript. It can be used as follows:
JS
|
1 2 3 4 |
Mousetrap.bind(['alt+x'], function() { alert('Alt + X pressed!'); return false; }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 |
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/mousetrap/1.6.3/mousetrap.min.js"></script> </head> <body> Press Alt + X </body> </html> |
That’s all about creating keyboard shortcuts in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)