Handling keyboard shortcuts in JavaScript

Handling keyboard shortcuts in JavaScript

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 key
  • keypress – fired once you press a key, which produces a character value like a letter or number, but not for special characters like CTRL
  • keydown – 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.

document.addEventListener('keyup', function (event) {
    console.log(event.key);
});

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.

// HTML code for a modal/help window
<div id="help" style="display:none; position:absolute; top: 25%; right: 25%; bottom: 25%; left: 25%; background: rgba(0, 0, 0, 0.5); ">
<h1>Help</h1>
<p>What seems to be the problem</p>
<ul>
    <li><a href="#">I don't remember my password</a></li>
    <li><a href="#">I want to add new user</a></li>
</ul>
</div>
// JavaScript code for modal/help window
document.addEventListener('keyup', function (event) {
    if (event.key === 'F1') {
        var element = document.getElementById('help');
        element.style.display = element.style.display === 'none' ? 'block' : 'none';
    }
});

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.

<div id="create" style="display:none; position:absolute; top: 25%; right: 25%; bottom: 25%; left: 25%; background: rgba(0, 0, 0, 0.5); ">
<h1>Create</h1>
<form>
    First name: <input name="first_name"><br>
    Last name: <input name="last_name"><br>
    Phone: <input name="phone"><br>
    <button type="submit">Save</button>
</form>
</div>

Now, let’s proceed with the required JavaScript code.

document.addEventListener('keyup', function (event) {
    if (event.ctrlKey && event.key === 'b') {
        
        var element = document.getElementById('create');
        element.style.display = 'block';
    }
});
// TODO if user clicked submit button then perform ajax request
// TODO once ajax request is done refresh view to show new contact and close the modal

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.