JS DOM - 03.04 - Events Related
Bubbling and capturing
The bubbling principle is simple. When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.
Bubbling and capturing lay the foundation for “event delegation” – an extremely powerful event handling pattern.
Event Delegation
The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.
In the handler we get event.target
to see where the event actually happened and handle it.
Browser action
There are many default browser actions:
mousedown
– starts the selection (move the mouse to select).click
on<input type="checkbox">
– checks/unchecks theinput
.submit
– clicking an<input type="submit">
or hitting Enter inside a form field causes this event to happen, and the browser submits the form after it.keydown
– pressing a key may lead to adding a character into a field, or other actions.contextmenu
– the event happens on a right-click, the action is to show the browser context menu.- …there are more…
All the default actions can be prevented if we want to handle the event exclusively by JavaScript.
To prevent a default action – use either event.preventDefault()
or return false
. The second method works only for handlers assigned with on<event>
.
The passive: true
option of addEventListener
tells the browser that the action is not going to be prevented. That’s useful for some mobile events, like touchstart
and touchmove
, to tell the browser that it should not wait for all handlers to finish before scrolling.
If the default action was prevented, the value of event.defaultPrevented
becomes true
, otherwise it’s false
.