Easiest Way to Create Keyboard Shortcuts in JavaScript

Robin
Updated on September 6, 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.

Detect the keyboard by listening to the keydown event in JavaScript. The key property from the event object gives access to the key a user pressed. Check if the ctrl, shift or alt keys were pressed or not. Finally, prevent the browser's default action and perform custom actions using if condition.

Let's see all the steps to create keyboard shortcuts in JavaScript in detail with examples.

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.

Easiest Way to Create Keyboard Shortcuts in JavaScript

Step 1: 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.

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

Step 2: Access Key and Add Keyboard Shortcuts

Now, I will extract the key user pressed on the keyboard using the event object. It provides different properties and methods related to a particular event like target, key, ctrlKey, shiftKey, altKey etc.

          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.

Step3: 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.

Step 4: 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.

Read Also: How to Change URL Dynamically Without Reloading Page in JavaScript

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.

Read Also: Check Internet Connection Offline/Online Using JavaScript in Browser

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.

Related Posts