Events, references
-
The
AbortSignal
interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object.-
Example: Exercises Part 4:
.removeEventListener()
andcontroller.abort()
Exercises and the most interesting parts
-
Exercises Part 1:
.addEventListener()
-
Exercises Part 2:
.addEventListener()
-
Exercises Part 3:
e.preventDefault()
-
Exercises Part 4:
.removeEventListener()
andcontroller.abort()
-
Exercises Part 5
event.target.nodeName
vsevent.currentTarget.tagName
-
Exercises Part 6
event.stopPropagation()
-
Exercises Part 7
Event delegation
-
Exercise: Move a Circle (source)
-
Exercise: Move a Circle with setInterval extends the above.
-
Exercise: Change color from data-attribute and use
event.target.matches('button')
(source) -
Event bubbling and capture. When an event is fired on an element that has parent elements, modern browsers run three different phases — the capturing phase, the target phase, and the bubbling phase.
Check MDN:
-
Introduction to events#Video player example
-
Introduction to events#Bubbling and capturing explained
-
Introduction to events#Fixing the problem with stopPropagation()
-
Introduction to events:The final fixed video player example
-
Example: Exercises Part 6
event.stopPropagation()
As we saw in the video example, this can be a very annoying behavior, but there is a way to prevent it! The standard
Event
object has a function available on it calledstopPropagation()
which, when invoked on a handler’s event object, makes it so that first handler is run but the event doesn’t bubble any further up the chain, so no more handlers will be run.video.addEventListener('click', e => { e.stopPropagation(); video.play(); });
-
-
Event delegation. Event bubbling isn’t just annoying though: it can be very useful. In particular it enables a practice called event delegation. In this practice, when we want some code to run when the user interacts with any one of a large number of child elements, we set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually.
- Example: Exercises Part 7
Event delegation
- Example: Exercises Part 7
-
Don’t use:
-
Event handler properties, like
btn.onclick = eventHandler;
- this is not flexible. -
Inline event handlers - don’t use these, like
<button onclick="bgChange()">
.It is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents.
-