JS Event capture & bubble-explained

anonymous·2022년 5월 30일
0

Event Bubbling and capturing

https://medium.com/developers-arena/understanding-preventdefault-stoppropagation-and-stopimmediatepropagation-when-working-with-61842c37e012

Event capturing

  • click event start from top and move to children
<div class="parent" (onClick)="console.log('parent')">
    <button class="child" (onClick)="console.log('child')"></button>
</div>

Result

parent
children

Event bubbling

  • inverse of event capturing, event moves from child to parent

event.preventDefault()

  • stop browser's default behavior
document.querySelector("#id-checkbox").addEventListener("click", function(event) {
         document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you check this!<br>";
         event.preventDefault();
}, false);

event.stopPropagation()

  • stop capture, bubbling phase of flow of event in browser
<div class="parent" (onClick)="console.log('parent')">
    <button class="child" (onClick)="buttonClick(event)"></button>
</div>
<script>
    function buttonClick(event) {
        event.stopPropagation();
        console.log('child');
    }
</script>

event.stopImmediatePropagation()

  • prevents multiple click listeners on single HTML element
  • stopImmediatePropagation = stopPropagation + other event listener
<script>
    $("div").click(function(event) {
      event.stopImmediatePropagation();
      alert('First click triggered');
    });

    $("div").click(function(event) {
      // This function won't be executed
      alert('Second click triggered');
    });
</script>
<div>Click me</div>
profile
기술블로거입니다

0개의 댓글