keydown and keyup fires when a user presses a key on the keyboard that’s NOT a character key. keydown goes first, followed by keyup. Non-character keys are:
Escape
F1 to F12
Delete (Backspace on PC)
Tab
Caps lock
Modifier keys like Shift, Control, Option (Alt on PC), Command (Windows on PC)
Arrow keys
(You can check for the type of event fired with event.type).
The first From document is caused by the tab key. It fires in the document.
The From button is fired by a space key on the button.
The last From document is caused by bubbling of the event to the document.
Avoid event delegation
You’ll want to avoid event delegation when dealing keyboard events. This is because an event might not fire if the user clicked inside the component (but not on an focusable element).
Then, user clicks on <form>, but not on <input> or <label>
If the user hits a key after (1), the event will bubble through <input>, <form>, and <document>.
If the user hits a key after (2), the focused element will be <body>. (I’ll explain how to check for the focused element in a later lesson). Since the focused element is <body>, <form> will not receive the keyboard event.
Getting the key that is pressed
You can get the value of a key with two properties:
key
code
key gets the value of the key that is pressed. It is case sensitive. If you press the e, you’ll get e. If you press shift + e, you’ll get E.
You can also use the getModifierState method to get the state of modifiers. You can use it to tell whether Shift, Control, Option, or Command are pressed.
getModifierState takes in an argument. It is a string that represents a modifier key. You can find a list of valid keys here.
In practice, getModifierState is only useful to tell whether the Caps Lock key is turned on.
You can trigger a click event from JavaScript. This is helpful when you create components. I’ll share more about this when you add keyboard interaction to Tabby.