const - JS | lectureDOM & Events Fundamentals

Project II - Handling Keypress Events

DOM & Events Fundamentals

In this lecture, we will learn how to handle KeyPress events. Right now, we can already close the modal by clicking the close button and by clicking outside of the modal. Usually, there is also a third way, and that's by hitting the escape key (Esc) on the keyboard.

It is a great use case to learn how to respond to keyboard events. So to listen for keyboard events, we still need to use addEventListener because the keypress event is just another type of event.

Now, keyboard events are so-called global events because they do not happen on one specific element. And for global events like keyboard events, we usually listen on the whole document. That is the same document we use for querySelector.

The document object is a big object which contains a bunch of methods for all kinds of stuff. That includes the addEventListener method. So by using addEventListener on document, we are listening for events everywhere. So no matter where they happen on the page, they will always trigger the event handler that we're going to specify.

When listening for keyboard events, when specifying the event type in the addEventListener method, there are actually three types of events for the keyboard .i.e. keydown, keypress or keyup.

  • keyup only happens when we lift our finger off the keyboard or the key.
  • keypress is fired continuously as we keep our finger on a certain key
  • keydown is fired as soon as we just press down the key.

Add the below code to your script file.

script.js
document.addEventListener('keydown', function () {
  console.log('A key was pressed');
});

If you now save and go to your browser, press any key, and it will print 'A key was pressed' in your console. However, we only want to close the popup when the escape key (Esc) is pressed.

The problem right now is that the event is being fired for all the keys that we press. The solution to this problem is that the information about which key was pressed will be stored in the event that is going to occur as soon as any key is pressed.

So what I mean is, as we hit any key on the keyboard, a keydown event is generated, and our listener function, .i.e. our handler function, is waiting for that event to happen. And anytime that an event like this occurs, JavaScript generates an object. That object contains all the information about the event itself, and we can then access that object in the event handler function.

Up until this point, we have never looked at that event. All we did was listening to the event and then reacting to it.

But now, we need to look at the event object to figure out which key was pressed. All we need to do is give our function handler a parameter called e which stands for event. The parameter name doesn't matter; it's just a matter of standards.

script.js
document.addEventListener('keydown', function (e) {
  console.log('A key was pressed');
});

When the event occurs, JavaScript will call this function (the event handler) with the event object as an argument. And once more, this works because we do not call this function ourselves. We only define it.

That is, we tell JavaScript: Hey, JavaScript call the function handler when a keydown event happens. And when you do so, please pass in the event object as an argument.

We will learn about the mechanics of this a bit better later. But it's still a good idea to already take note of this stuff we are talking about.

Now that you know why this function has access to an event (e), let's now actually take a look at it.

script.js
console.log(e);

Save everything, then go to your browser and hit any key on your keyboard, and you should see something similar to the below image.

Keyboard Event

You can see that in our console, we have something called KeyboardEvent. It is just an object that JavaScript generates. It looks like the objects we generated ourselves in our previous lectures. That is, with a key and a value.

What matters here is the key property, which we can see on the KeyboardEvent object. I hit the Shift key in my case, and then this event was generated with the key property set to Shift.

Now that we can know which key was pressed by using the key property from our KeyboardEvent object, we can use that information to close the modal whenever the escape key is pressed.

script.js
if (e.key === 'Escape') {
  console.log('Escape was pressed');
}

However, I only want to close the modal when the modal is visible. To know if the modal is visible, we can check if the modal contains the hidden class. If it does, it means that it's not visible. And so basically, when it does not contain the class hidden, it means that it's visible and then that's the condition in which we want to close it.

So to check if our modal does not contain the hidden class, here is what we have to do:

script.js
if (e.key === 'Escape') {
  //We only want to close the modal if it does not contain the hidden class—reason why we inverted the boolean value.
  if (!modal.classList.contains('hidden')) {
    // All that is now left for us is to call our closeModal function
    closeModal();
  }
}

To finish, let's improve our code a little. If you try reading the above code, it says, 'If the pressed key is Escape AND the modal does not contain the hidden class, then close the modal.'. You can notice the AND in the sentence, which means we can aggregate the two if statements together.

script.js
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
  closeModal();
}

With this, our modal is feature complete. I hope you liked this second mini-project and that you can now see how powerful DOM manipulation can be. In the next lecture, we will start another very exciting project! So stay tuned.