DEV Community

Cover image for Event Propagation: Capturing, Bubbling
uu
uu

Posted on

Event Propagation: Capturing, Bubbling

DOM event flow has three phases: Capture, Target, Bubbling phase.

<html>

<head>
    <title>Event Propagation</title>
    <style>
        #parent {
            width: 200px;
            height: 200px;
            text-align: center;
            line-height: 3;
            background: green;
        }

        #child {
            width: 100px;
            height: 100px;
            margin: 0 auto;
            background: orange;
        }
    </style>
</head>

<body>
    <div id="parent">
        Parent element
        <div id="child">
            Children element
        </div>
    </div>
    <script type="text/javascript">
        var parent = document.getElementById("parent");
        var child = document.getElementById("child");

        document.body.addEventListener("click", function (e) {
            console.log("click-body");
        }, false);

        parent.addEventListener("click", function (e) {
            console.log("click-parent");
        }, true);

        child.addEventListener("click", function (e) {
            console.log("click-child");
        }, false);
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Event Capturing

When clicking mouse or triggering dom event(here click child's div), browser will propagate event from outside to target,starting from root(document).

See the code above, parent's listener were registered using a value of true in addEventListener

parent.addEventListener('click', listener, true)
Enter fullscreen mode Exit fullscreen mode

If third parameter is omitted, its default value is false and the listener is not a capturer. Then it is not event capturing, event bubbling instead.

Event Bubbling

Event Bubbling is other way around. Its event order is from target to outside(can be parent), going up back to root.

child.addEventListener("click", function (e) {
            console.log("click-child");
        }, false);
Enter fullscreen mode Exit fullscreen mode

Alt Text

Summary

1.Event Propagation order : Capturing -> Target -> Bubbling
2.When event reaches target itself, all the listeners registered on the event target will be invoked, regardless of event capturing(true) or event bubbling(default or false).

Top comments (0)