Skip to content

Bubbling and Trickling

  • Event propagation in the DOM happens in three phases:
    • Trickle down from the root to the target element.
    • Reach the target element.
    • Bubble up to the root again. Some events, such as focus and blur, do not participate in this phase.
  • e.stopPropagation() stops the event from propagating further in the current direction of the propagation phase.
  • By default, useCapture is false.

HTML

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    div{
        margin: auto;
        min-height: 40px;
        min-width: 40px;
        border: 1px solid black;
        padding: 30px;
    }
</style>
<body>
    <div id="grandparent">
        <div id="parent">
            <div id="child"></div>
        </div>
    </div>
</body>
<script src="./bubbling-trickling.js"></script>
</html>

JavaScript

js
document.querySelector('#grandparent').addEventListener('click',(e)=>{
    console.log("Grandparent called")
},false)

document.querySelector('#parent').addEventListener('click',()=>{
    console.log("Parent called")
},true)

document.querySelector('#child').addEventListener('click',(e)=>{
    e.stopPropagation()
    console.log("Child called")
},false)