source: http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing
question: What is the difference between event bubbling and capturing? Of the two, which is the faster and better model to use?
answer:
question: What is the difference between event bubbling and capturing? Of the two, which is the faster and better model to use?
answer:
Event bubbling and capturing are two ways of event propagation in HTML DOM.
In bubbling the event is first captured and handled by the inner most element and then propagated to outer elements.
In capturing the event is first captured by the outer most element and propagated to the inner most element.
During the time of Netscape browser they were advocates of event capturing and Microsoft was from event bubbling school.
Both are part of the W3C standard. As per the standard first the event will capture it till it reaches the target then it will bubble up to the outer most element.
IE uses only event bubbling where as firefox supports both bubbling and capturing.
We can use the
addEventListener(type, listener, useCapture)
to register event handlers for bubbling and capturing phases. To use the capturing phase event handling pass the third argument as true
.
Only event bubbling model is supported by all the major browsers. So if you are going to use event capturing still you need to handle event bubbling for IE. So it will easier to use event bubbling instead of capturing.
<div>
<ul>
<li></li>
</ul>
</div>
If you take this structure and assume that a click event has happened in the
li
element.
In capturing model the event will be handled by the
div
first(click event handlers in the div will fire first) then in the ul
then at the last in the target element li
.
In bubbling model it is the opposite. In this model the event will be first handled by the
li
first and the ul
and at the last by the div
element.Event capturingWhen you use event capturing| | ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 \ / | | | ------------------------- | | Event CAPTURING | -----------------------------------
the event handler of element1 fires first, the event handler of element2 fires last.Event bubblingWhen you use event bubbling/ \ ---------------| |----------------- | element1 | | | | -----------| |----------- | | |element2 | | | | | ------------------------- | | Event BUBBLING | -----------------------------------
the event handler of element2 fires first, the event handler of element1 fires last.
What to use?
It depends on what you want to do. There is no better. The difference is the order of the execution of the event handlers. Most of the time it will be fine to fire event handlers in the bubbling phase but it can also be necessary to fire them earlier.
댓글
댓글 쓰기