Interactive online courses HTML Academy
2026-03-09 12:24 Diff

The popup already opens and closes when it is clicked. All that we have left to do is add the code so that the popup closes when the ESC key is pressed.

We sort of figured out how to do it by clicking on a button, but how do we arrange for a handler to be created at the press of a button?

The “keystroke” event has a special name: keydown. This is an event that is triggered by a keypress. It is important to note that you can only listen for this event using elements that are in focus: input fields, buttons, and elements with the tabindex and document attributes. When you press the button, the focus should shift to the corresponding element.

document.addEventListener('keydown', function() { // The code here is executed every time that you press a key. });

Add a keypress handler to the document, and verify how it works.

Please note: In order to make sure that the handler is able to respond to keystrokes, you need to make sure that our mini-browser is in focus. Click inside the mini-browser in order to make the window active. In ordinary life, you wouldn’t need to do this, but in our interface the mini-browser is built into a regular browser, so you need to make JavaScript understand where you are right now.