Easiest Way to Create Keyboard Shortcuts in JavaScript

Robin
April 3, 2022

To provide a better user experience on your website, you can create custom keyboard shortcuts in JavaScript. It not only gives convenience but also saves time when someone uses your website or web application.

If you are interested, you are at the right place.

In this article, you will learn how you can add custom keyboard shortcuts using JavaScript and override the default browser keyboard shortcuts.

Read Also: Input VS Change VS Blur VS Focus | JavaScript Events

Let’s start.

Prerequisites

The only prerequisites for this tutorial are that you should have a basic understanding of JavaScript concepts, like DOM events, EventListener, Conditions, DOM selection etc.

I will explain every step in detail so that you don’t have any confusion on this topic and you can easily extend the logic further to meet your website requirements.

Easiest Way to Create Keyboard Shortcuts in JavaScript

What is Keyboard Shortcut in JavaScript?

The keyboard shortcut is the way to perform some function by just pressing one or more keys on a keyboard. When we want to add such shortcuts to our website, we need to use JavaScript.

It provides many benefits to the users. Like, By using shortcuts you can work faster and be more productive because you don’t need to move your hand between the keyboard and the mouse.

Keyboard shortcuts are more effective if you type or use a keyboard while using the website. On such websites, we try to add shortcuts for the most used features for our users.

Create Keyboard Shortcuts in JavaScript

To create custom keyboard shortcuts in JavaScript, you have to follow a few steps. These are the following steps:

  • You need to detect the keyboard in your website using addEventListener() method to the document.
  • Listen keydown event to extract the keys a user pressed on the keyboard.
  • You can extract the keys by accessing key property from the JS event object.
  • To check whether a user is pressing ctrl, shift or alt keys, you can use ctrlKey, shiftKey or altkey properties in the JS event object.
  • Finally, inside addEventListener() callback function add if condition using the keys you have extracted earlier to apply your functionality.

Note: If you want to override the default shortcuts provided by the browsers, you have to use preventDefault() method from the JS event object.

These are the steps you need to use in order to trigger custom shortcuts on your website. If it feels complicated, don’t worry. Now I will discuss every step in detail.

Detecting Keyboard in a Website

To detect keyboards on our website I will apply addEventListener() method on the document.

document.addEventListener('keydown', (e) => {
    // I will add logic later
});

Here, I am listening to keydown event. There is another event called keyup. You can also use this event. But sometimes keyup event creates conflict with the default shortcuts. It is safe to use keydown event.

In the callback function, e is the event object that provides all the necessary information about the event and the keys that a user presses.

What is JavaScript Event Object?

Whenever any event takes place in the DOM, JavaScript provides an object with many properties and methods related to that particular event. This is known as a JavaScript event object.

You can access properties like target, key, ctrlKey, shiftKey, altKey etc. It also gives methods like preventDefault().

You can learn more about the event object here.

Access Key and Add Keyboard Shortcuts

Now, I will extract the key user pressed on the keyboard using the event object.

document.addEventListener('keydown', (e) => {
    if (e.key.toLowerCase() === 's') {
        // Add your code here
        alert('S key pressed');
    }
});

I am accessing the key that the user pressed using e.key. I have added toLowerCase() method to convert the letter to lowercase. Because I am checking if the letter is equal to the lowercase “s”.

It is safe to use this method in case we get uppercase “S” for a user. Then code inside the if statement will not run.

You can compare it with any key you need for your website. I am using “s” here just to give you an example.

Track if ctrl, shift or alt Key is Pressed

Sometimes you may need to check if the key is pressed with the ctrl, shift, or alt keys. You can also check it using the event object.

document.addEventListener('keydown', (e) => {
    if (e.key.toLowerCase() === 's' && e.ctrlKey) {
        // Add your code here
        alert('S key pressed with ctrl');
    }
});

Now, I am checking in the condition whether the user pressed the letter “s” with the ctrl key by accessing e.ctrlKey property.

This property gives a boolean value i.e. it will be true or false. If the user press ctrl key and “s” key together, then code inside the if statement will run.

Note: You can do the same this using e.shiftKey and e.altKey properties. Both of them works exactly like e.ctrlKey property.

How to Override Browser Default Keyboard Shortcuts in JavaScript

If you press the “s” with ctrl key, the browser will also try to save the document by default. Because it is the default keyboard shortcut in most web browsers.

But you might not want that to happen. To prevent the default behavior in a web browser, you just have to add one line of code.

document.addEventListener('keydown', (e) => {
    e.preventDefault();

    if (e.key.toLowerCase() === 's' && e.ctrlKey) {
        // Add your code here
        alert('S key pressed with ctrl');
    }
});

I just added e.preventDefault() in the callback function to prevent any default keyboard shortcuts. Now, any default shortcuts provided by the web browser will not work on my website.

But if you don’t want to prevent all default shortcuts, you can add e.preventDefault() inside the if statement.

document.addEventListener('keydown', (e) => {
    if (e.key.toLowerCase() === 's' && e.ctrlKey) {
        e.preventDefault();

        // Add your code here
        alert('S key pressed with ctrl');
    }
});

Now, if you press the letter “s” with ctrl key, it will run your code and prevent the default browser shortcut. But other default shortcuts will work.

How to Add Multiple Keyboard Shortcuts in JavaScript

Until now, I have added a single keyboard shortcut to my website. But what will happen if I need multiple shortcuts.

document.addEventListener('keydown', (e) => {
    if (e.key.toLowerCase() === 's' && e.ctrlKey) {
        e.preventDefault();
        // Add your code here
        shortcutForCrtlS();
    } else if (e.key.toLowerCase() === 'p' && e.shiftKey) {
        // Add your code here
        shortcutForShiftP();
    } else if (e.key.toLowerCase() === 'i' && e.altKey) {
        // Add your code here
        shortcutForAltI();
    }
});

In this example, I am checking for 3 keyboard shortcuts using 3 if and else if statements. These are ctrl + s, shift + p and alt+i.

You can add your logic according to your need in between those conditional statements.

How to Add Keyboard Shortcuts in JavaScript for Specific HTML Element

There might be a situation where you don’t want to add shortcuts for the global document. But you need to add them for specific input on your webpage.

For example, you have an <input> field with id “title”, you want to add shortcuts for that input only.

document.getElementById('title').addEventListener('keydown', (e) => {
    if (e.key.toLowerCase() === 's' && e.ctrlKey) {
        e.preventDefault();
        // Add your code here
        alert('S key pressed with ctrl');
        shortcutForCrtlS();
    } else if (e.key.toLowerCase() === 'p' && e.shiftKey) {
        // Add your code here
        alert('p key pressed with shift');
        shortcutForCrtlP();
    } else if (e.key.toLowerCase() === 'i' && e.altKey) {
        // Add your code here
        shortcutForCrtlI();
        alert('i key pressed with alt');
    }
});

In this example, I am selecting the <input> field using getElementById() method and then listening to keydown event by adding addEventListener() method to it.

Now the shortcuts ctrl+s, shift+p, and alt+i will only work when our <input> field is in focus. Other rules are the same as the previous ones.

Create Keyboard Shortcuts using JavaScript Library

You have seen manual ways to create custom shortcuts. But if you don’t like to do this from scratch then there are many JavaScript libraries to use like Mousetrap, KeyboardJS, Keymaster, etc.

These libraries will simplify the process but for small use, I would prefer to do this using plain JavaScript. Because If you don’t use most of the features of these libraries then it is unnecessary to install.

They will just increase the bundle size and page loading time. If you need many features that those libraries provide then it will be a good choice to use them.

Conclusion

That’s it. Congratulations, you have learned to create keyboard shortcuts in JavaScript. You can easily implement this concept on your website to give additional features to visitors.

You have also seen how to override the default keyboard shortcuts provided by the browsers. That’s all you need to know on this topic.

I hope you have enjoyed the lesson. Happy codding!

Related Posts