Keyboard shortcuts are not only for desktop applications. You can also create shortcuts for web applications, which can come in handly in your MPA or SPA apps. Read on to find out how to create keyboard shortcuts in JavaScript.
The key events
Inside web browsers we have 3 distinct events related to keyboard events.
keyup
– fired after you release a keykeypress
– fired once you press a key, which produces a character value like a letter or number, but not for special characters like CTRLkeydown
– fired after you press a key
We can use these events to call desired function. You can attach events to chosen input fields. Since we want it to work (almost) like a desktop app, we’ll attach the event handler to document. Also, the event handler has one parameter which contains all event properties.
The keypress
event is deprecated and we won’t be using it. In general prefer keydown
over keypress.
You should also be aware that the keydown
event executes multiple times when you hold down the keyboard button, while keyup
fires only once per button.
Keylogging
Let’s start with most basic example, which is a simple keylogger. It will grab all the keys and print them in your browsers console window.
|
|
Go ahead and try it.
Notice that it also handles special characters like CTRL, ALT and shift, respecitvely as: Control, Alt, Shift. You should also know that all 3 can also be handled by other event properties which are ctrlKey
, altKey
, shiftKey
which indicate wheter or not one of this keys has been pressed. Typically for shortcuts you would use these properties to check wheter it’s a CTRL+A or CTRL+SHIFT+A.
Help window
Typically F1 is used to open some kind of help window. Let’s try to implement this kind of function. Whenever user presses F1 we’ll toggle a modal window with some instructions.
|
|
|
|
Create new contact window
One last example. It is common in desktop applications that the CTRL+N shortcut creates a new entry. We’re going to make something just like that. It’s very similar to help window we did before.
There is a “but”, most likely the CTRL+N shortcut is going to be handled by your browser, which will either open new browser window or new browser tab. Because of that we’ll use a different shortcut CTRL+Y. As it seems some of the key combinations are disallowed, so you won’t be able to override it.
Our modal window will contain a form with first name, last name and phone number fields.
|
|
Now, let’s proceed with the required JavaScript code.
|
|
If you want to learn how to create more advanced modals using ajax requests to save the data then check out my other article Bootstrap ajax modals.