What gets logged when you click the inner div?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>What gets logged?</title> <style> #outerDiv { background-color: lightgrey; padding: 50px; border: 2px solid black; text-align: center; } #innerDiv { background-color: lightcoral; padding: 20px; margin: 20px; border: 2px solid black; text-align: center; } </style> </head> <body> <div id="outerDiv"> Outer Div <div id="innerDiv">Inner Div</div> </div> <script> const outerDiv = document.getElementById("outerDiv"); const innerDiv = document.getElementById("innerDiv"); outerDiv.addEventListener( "click", (e) => { console.log("Outer div clicked!", e.target); }, true ); innerDiv.addEventListener( "click", (e) => { e.stopPropagation(); console.log("Inner div clicked!", e.target); }, false ); </script> </body> </html>
What gets logged when you click the inner div?
// Outer div clicked! <div id="innerDiv">Inner Div</div> // Inner div clicked! <div id="innerDiv">Inner Div</div>
Even though stopPropagation() is called in the child’s event handler, the parent’s event handler still executes because it’s set to capture, and it executes before the event reaches the child in the capturing phase.
If the parent’s event handler was set to bubble, then the child’s event handler would execute first, and the parent’s event handler would not execute at all because the event would have been stopped in the child’s event handler.
Lastly, the target property of the event object is always the element that the event was dispatched to, which is the inner div in this case.