Event
An Event is a signal fired by the browser whenever something happens.
Events are fired within the context of a single browser window, and must take place "attached" to an EventTarget.
A system can respond to events through event handlers using addEventListener()
.
INFO
Event handler and event listener are interchangable terms.
But, if you want to be a real stickler, then an event listener is just the bit which listens for the event. The event handler is the callback.
const button = document.querySelector("button");
/* ... suppose this part is the listener ... */
button.addEventListener("click", () => {
/* ... this part is the handler ... */
});
All events have shared properties like Event.type
or Event.timeStamp
.
Builtin events
There are a number of builtin events for responding to common browser happenings, like mouse clicks or key presses.
All mouse related events use MouseEvent
.
See Event reference
Keyboard events
All keyboard related events use KeyboardEvent
.
To get the key from a KeyboardEvent, use the .key
property.
See Key values for keyboard events - Web APIs | MDN
See Key.js for keycodes relating to keyboard events
Custom events
Custom events can be made using the regular base Event
class constructor for anything which doesn't require custom data dispatched alongside the event.
const wave = new Event("wave", { /* custom non-data options here */ });
// hi!
document.dispatchEvent(wave);
For any events which do need custom data, use the CustomEvent
class constructor.
const greeting = new CustomEvent("wave", { detail: { from: "Jim" }});
document.addEventListener("wave", ({ detail: { from }}) => {
console.log(`Waving back to ${from}!`);
});
// Waving back to Jim!
document.dispatchEvent(greeting);
See Creating and triggering events
Event bubbling
Events by default will "bubble" up to their respective parent elements in the DOM.
Bubbling up here just means that the event can be caught by parent elements.
For a DOM like:
<body>
<div id="container">
<button id="increment">Increment</button>
</div>
</body>
Then dispatching a click
event to the button would cause the same event to be caught on the container and in the body.
As in:
const handleClick = () => console.log("hee hee you clicked mee mee");
document.body.addEventListener("click", handleClick);
document.querySelector("#container").addEventListener("click", handleClick);
document.querySelector("#increment").addEventListener("click", handleClick);
If the button was clicked, the message would be logged three times.
To prevent or alter this behaviour, you can:
stopPropagation()
, call all other event handlers on this level and then stopstopImmediatePropagation()
, fire this on no other event handlers
See Event bubbling.