what is capture mode on an event listener

So right after posting I stumbled on this article which illustrates it clearly. Let's say for this example that you have three elements nested within each other:

<div class="outer">
    <div class="middle">
        <div class="inner"></div>
    </div>
</div>

When a click event occurs, there are two phases: the first is called capturing, the second is called bubbling. When you click on the .inner, the event traverses down from the outermost container element .outer, to .middle, then to .inner in the capturing phase, then from .inner to .middle, then to .outer in the bubbling phase.

If capture is set on .inner for a click event handler:

<div class="outer">
    <div class="middle">
        <div class="inner" v-on:click.capture="doThis"></div>
    </div>
</div>

and you click on it, it will hit .outer, then .middle, then .inner in the capture phase, which will cause doThis(...) to be called, after which the bubbling phase begins.

If capture is set on .middle for a click event handler

<div class="outer">
    <div class="middle" v-on:click.capture="doThis">
        <div class="inner"></div>
    </div>
</div>

and you click on it, it will hit .outer, then .middle, in the capture phase, which will cause doThis(...) to be called, then hit .inner in the capture phase, after which the bubbling phase begins.

Edit: Thanks for all the great responses below, I've amended the answer to fix where I was incorrect.


Both bubble and capture event handlers on an element will be triggered only once, the difference is when they are triggered (before the children or after the children). Capture mode means the handler is triggered before any handlers on child elements. Bubble mode (the default), means the handler is triggered after all child elements have finished their handlers. You can even put a capture mode and bubble mode event handler by doing <div v-on:click="doThis" v-on:click.capture="doThis">

This JS fiddle demonstrates how a single click to a nested inner element first triggers capture handlers in an "outer-to-inner" order, and then triggers bubble handlers in an "inner-to-outer" order.

Tags:

Vue.Js