Many people have explained that e.stopPropagation()
prevents event bubbling. However, I\'m having a hard time finding why one would want or want to
Do not use stopPropagation()
, if possible.
Two advantages using stopPropagation()
are:
Although this function seems to be useful, it can be considered bad coding style, especially when you have no full control over the code (e. g. because you use a third-party library). stopPropagation()
is a take-everything-or-nothing concept. It does not allow fine control flow. If some element between two other nested elements stops the event propagation, none of the parent elements will receive it, although there might be situations, when they should receive it.
A more elegant (and not that complex) way to solve this problem, is to always allow the event propagation by never calling stopPropagation()
at all. Elements, which define their own events which shall not be automatically executed from a child element, can use the target and currentTarget properties to check from where the initial event comes and execute own event functions only in situations when it is wanted.
In following example, there are 3 nested DIVs. Clicking the lowest (blue) DIV shall propagate the onClick event up through the entire DOM structure but without calling the onClick event of the green DIV, which lies between:
So calling stopPropagation()
in onClick event function of DIV #3 is not necessary required to prevent firing the onClick event if DIV #2.
Also note, that the document structure is as follows:
document
document.documentElement
document.body
...
If an event propagation is not stopped, it will reach the document
object. event.currentTarget
will then be document
, while event.target
will be either document.documentElement
, document.body
or any sub element under the element.
So considering you have following code:
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
Here is what it looks like and where the different parts of the document are:
Gray is the body area. Green is the actual document "element" (top most styleable part). And behind it, there is the invisible document
object.
If you want to use event functions, which will be executed only for the elements directly under your finger / mouse cursor, you could use following code (example for onClick event):
elm.addEventListener('click', function(e) {
if
(
(
(e.currentTarget == document) &&
(e.target == document.documentElement || e.target == document.body)
)
||
(e.currentTarget == e.target)
)
{
// ...
}
});
It works with document.documentElement
, document.body
or any element on the document without needing to call stopPropagation()
.