Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Choosing a key
We called the event, and it is triggered when we press any key. But any key won’t do. We need to use ESC
. How can we execute the code by pressing just one specific key? Let’s turn our attention to the event
object, which we are already familiar with.
We previously mentioned that the event object has many useful properties. For example, the event type, entered character, the cursor coordinates at the time the event occurred, and much more. These also include the code of the key that the user pressed. This property is called keyCode
.
We can use this property to identify every key by code. For example, Enter
has the code 13
, whereas ESC
has the code 27
. These numbers are universal and the same for any layout. You can find the code for any key here.
We now know that we have the event
object, which contains the number of the pressed key in the keyCode
property, and we know the code of the desired key. The only thing left to do is collect all of this information into a single handler.
document.addEventListener('keydown', function(evt) {
// Let's check that the key code is equal to 27.
if (evt.keyCode === 27) {
// The code is only executed when ESC is pressed.
}
});
Let’s configure our handler so that the instructions are executed only when ESC
is pressed.
there are other properties besides keyCode
for determining the pressed key. There is key, for example. It is different due to the fact that it doesn’t return the key code, but rather its name in the form of a string: “Enter”, “Alt”, and “Escape”. We also have the code property. It also returns the name of the key. In this case, the selected keyboard language does not have any influence on the value. These properties are not yet supported in all browsers, but when they are implemented more widely, you should start using them instead of the keyCode
in accordance with the modern JavaScript standard.
- index.html
- style.css
- script.js
Thanks! We’ll fix everything at once!
Click inside the mini browser to put the focus in this window.
- Add the
evt
parameter to the keyboard event handler function. - Check that the code of the pressed
evt.keyCode
key is equal to27
inside the handler. - Delete the console output from the handler, and add the console output of the string
'I pressed ESC'
to the condition body. - Set focus to the mini-browser, press
ESC
on the keyboard, and check the message in the console.
Comments