Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Advertisement
  1. Code
  2. JavaScript

Catching and Responding to Keyboard Events in JavaScript

by
Read Time:7 minsLanguages:

In this article, we’ll discuss how you can catch and respond to different keyboard events in JavaScript. I'll show you a couple of real-world examples to make it easy to understand.

JavaScript is one of the core technologies of the web. The majority of websites use it, and all modern web browsers support it without the need for plugins. In this series, we’re discussing different tips and tricks that will help you in your day-to-day JavaScript development.

As a JavaScript developer, sometimes you need to implement features that require you to deal with keyboard events and perform actions based on them. Luckily, JavaScript provides a built-in KeyboardEvent object, which allows you to handle different types of keyboard events.

Keyboard Events in JavaScript

In JavaScript, the KeyboardEvent object provides three events: key down, keypress, and key up.

When you press any key on the keyboard, a series of events take place in the following order.

  • key down
  • keypress
  • key up

When you press down any key on the keyboard, the key down event is triggered. And if a key is pressed for a long time, the key down event is repeatedly triggered.

The keypress event is mostly triggered when you press down any printable character, and it’s fired after the key down event. In fact, the keypress event is used to relay a character resulting from the key down event. Mostly, the keypress event is not raised by non-character keys. Although some browsers support this event, it’s not recommended to rely on this event, as it’s going to be removed from the web standards.

Keypress events are deprecated and will be phased out of modern browsers.

Finally, the key up event is raised when a key is released. Basically, a combination of key down and key up events provide you a code which indicates the key which was pressed.

Each keyboard event provides two important properties: key and code. The key property is populated with the character which was pressed, and the code property is populated with the physical key location of the character. As an example, if you press the a character key, the key property is populated with a, and the code property is populated with the KeyA constant. However, the key code pressed is not necessarily the same as the character! If a user has set up an alternate keyboard layout, for example Dvorak, then pressing the same key code will produce a different character.

So that was a brief overview of keyboard events in JavaScript. Starting with the next section, we’ll discuss these events along with real-world examples to understand how they work.

The keydown Event

In this section, we’ll see how the keydown event works in JavaScript. The keydown event is triggered when any key is pressed on the keyboard.

Let’s quickly go through the following example.

As you can see, we’ve created a listener to listen to the keydown event. Whenever any key is pressed, our listener is called, and it logs values of the key and code to the console. Go ahead and run it to see how it works.

Let's go through the following example, which demonstrates how you can detect if the user has pressed ctrl + a or ctrl + A.

Firstly, ctrlKey is a special property of the KeyboardEvent object, which tells you whether the Ctrl key was pressed when the keydown event was triggered. So if ctrlKey is  true, it means that the Ctrl key was pressed.

Next, we checked the keyCode value of the character which was pressed, if it’s either 65 or 97, it means that either a or A was pressed along with the Ctrl key. The keyCode property of the KeyboardEvent object returns the Unicode character code of the key which was pressed. Similarly, you can also use the shiftKey property of the KeyboardEvent object, which tells you whether the Shift key was pressed when the key down event was triggered.

Finally, let’s go through the following example, which demonstrates how you can allow only alphabets in the input field of an HTML form.

In the above example, we’ve defined the keydown event on the input text box. So when the user enters any text in the textbox, it calls the allowOnlyAlphabets function. In the allowOnlyAlphabets function, we’ve validated the value of the keyCode property of the event object against the valid Unicode range for alphabets. Thus, if the user presses a valid alphabet character, the allowOnlyAlphabets function returns true, otherwise it would return false. The end result is that the user won’t be able to type any characters but the alphabet.

The keyup Event

In this section, we’ll see how the keyup event works. In fact, it works pretty similarly to the  keydown event with the only difference is that it’s triggered when the key is released instead of when the key is pressed.

Let’s go through the following example.

In the above example, when you press any key, it would first trigger the keydown event followed by the keyup event. For example, if you press the a key, you should see the following output on the console. It’s important to note the order of events that are triggered.

Let’s go through the following example, which demonstrates how you can use the keyup event in your projects.

In the above example, we’ve defined the onkeyup event on the input text box. So when the user enters any text in the textbox, it calls the getSearchResults function. In the getSearchResults function, we’ll make an AJAX call to fetch search results for the search keyword. This is also called live search, since it will display search results instantly without refreshing the whole page.

Important KeyboardEvent Object Properties

In this last section, I’ll summarize important properties of the KeyboardEvent object. In fact, we’ve already seen a couple of commonly used properties like key and code in the examples that we’ve discussed so far. There are also a few other important properties that we’ll discuss in this section.

  • key: returns the character which is pressed. For example, if the a character is pressed, it would return a.
  • code: returns the physical key code of the character. For example, if the a character is pressed, it would return KeyA.
  • keyCode: returns the Unicode character code of the key which is pressed.
  • ctrlKey: tells you whether the Ctrl key was pressed when the key event was triggered.
  • altKey: tells you whether the Alt key was pressed when the key event was triggered.
  • shiftKey: tells you whether the Shift key was pressed when the key event was triggered.
  • metaKey: tells you whether the Meta key was pressed when the key event was triggered. In most cases, the Meta key is the key which is between the Ctrl and Alt keys on your keyboard.
  • location: returns the location of a key on the keyboard or device.

As you can see, the keyboardEvent object provides various properties that allow you to detect different keys. In most cases, you will use the keydown event to detect keys that were pressed and perform corresponding actions. And as we discussed earlier, you should not use the keypress event, since it’s going to be deprecated sooner or later.

Conclusion

Today, we discussed how you can work with keyboard events in JavaScript along with a couple of real-world examples.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.