Events
Last updated
Was this helpful?
Last updated
Was this helpful?
Events are used to signal that something in the DOM has happened. Some events are user-generated, such as mouse or keyboard events, while others are generated by side effects such as videos being paused or an animation that has finished running.
The most intuitive event is perhaps the click
event. It is fired when a user clicks on an element inside the DOM. Events are passed as arguments to the click handler.
Let's alert
a string when a user presses the Howdy
button.
To receive the click
event when the user press Howdy
we need to register an event listener. Listeners are functions that are scheduled to run when an event is fired. Just like setTimeout
and setInterval
.
First we select the element that we want to listen for the event on.
Next we add an event listener that alerts our greeting when the event is fired.
Another class of events that are typically fired are the ones associated with keypresses. A keypress usually fires the following events:
When the key is first depressed, the keydown
event is sent.
If the key is not a modifier key (Shift etc.), the keypress
event is sent.
When the user releases the key, the keyup
event is sent.
Each key has a unique keyCode
property that represents it. We use the keyCode
to determine which key was pressed.
Key
Code
a
65
b
66
c
67
...
...
←
37
.→
38
.↑
39
.↓
40
...
...
F1
112
F2
113
F3
114
Imagine that we want to alert
when one of the arrow keys (↑
, ↓
, ←
, →
) are pressed down (keydown
) anywhere within the DOM.
We register an event handler that can distinguish between arrow keys from all the other keys. To do so we check if the keyCode
on the event
lies between 36 and 41.