DOM Event

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Event Listener</title>
    <link rel="stylesheet" href="style.css" />
    <script src="./script.js" defer></script>
  </head>
  <body>
    <div class="grandparent">
      <div class="parent">
        <div class="child"></div>
      </div>
    </div>
  </body>
</html>

Add Event(์ด๋ฒคํŠธ ๋“ฑ๋ก): addEventListener

  • ๋™์  ๊ธฐ๋Šฅ(์‚ฌ์šฉ์ž ์ž…๋ ฅ ๋“ฑ) ์ถ”๊ฐ€

    document.addEventListener("click", (e) => {
      console.log("Document", e.target);
    });

Event Capturing(์ด๋ฒˆํŠธ ์บก์ฒ˜๋ง)

  • Capture In

  • ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ํ•˜์œ„ ์š”์†Œ๋กœ ์ด๋ฒคํŠธ ์ „๋‹ฌ

  • Document > HTML > body > div > button(event target)

    • addEventListener์— capture:true ์˜ต์…˜ ์ถ”๊ฐ€

      grandparent.addEventListener(
        "click",
        (e) => {
          console.log("Grandparent", e.target);
        },
        { capture: true }
      );

Event Bubbling(์ด๋ฒˆํŠธ ๋ฒ„๋ธ”๋ง)

  • Bubble Out

  • ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ์ƒ์œ„ ์š”์†Œ๋กœ ์ด๋ฒคํŠธ ์ „๋‹ฌ

  • button(event target) > div > body > HTML > Document

stopPropagation

  • ์ด๋ฒคํŠธ ์ „๋‹ฌ ๋ฐฉ์ง€

    parent.addEventListener(
      "click",
      (e) => {
        e.stopPropagation(); // event delivery stops at "Parent Capture"
        console.log("Parent Capture", e.target);
      },
      { once: true }
    );

option: once

  • ํ•œ๋ฒˆ๋งŒ ์‹คํ–‰ํ•˜๊ณ  ์ œ๊ฑฐ

    • addEventListener์— once:true ์˜ต์…˜ ์ถ”๊ฐ€

      parent.addEventListener(
        "click",
        (e) => {
          console.log("Parent Capture", e.target);
        },
        { once: true }
      );

Remove Event(์ด๋ฒคํŠธ ์ œ๊ฑฐ): removeEventListener

  • ํ• ๋‹น๋œ ์ด๋ฒคํŠธ ์ œ๊ฑฐ

    //*** Remove printHi event after 2 seconds
    parent.addEventListener("click", printHi);
    
    setTimeout(() => {
      parent.removeEventListener("click", printHi);
    }, 2000);
    
    function printHi() {
      console.log("Hi");
    }

Event Delegation(์ด๋ฒคํŠธ ์œ„์ž„)

  • ์ด๋ฒคํŠธ ์บก์ฒ˜๋ง๊ณผ ๋ฒ„๋ธ”๋ง ํ™œ์šฉํ•˜์—ฌ ์ด๋ฒคํŠธ ์œ„์ž„ ๊ตฌํ˜„

  • ์š”์†Œ๋งˆ๋‹ค ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ๋ฅผ ํ• ๋‹นํ•˜์ง€ ์•Š๊ณ , ์ƒ์œ„ ์š”์†Œ์—์„œ ํ•˜์œ„ ์š”์†Œ์˜ ์ด๋ฒคํŠธ ์ œ์–ด

onst divs = document.querySelectorAll("div");

// ์ƒ์œ„ ์š”์†Œ document์— ํด๋ฆญ์ด๋ฒคํŠธ ํ• ๋‹นํ•˜์—ฌ ๋ชจ๋“  ์ž์‹ ์š”์†Œ ์ œ์–ด
// ํ•˜์œ„์—์„œ ๋ฐœ์ƒํ•œ ํด๋ฆญ ์ด๋ฒคํŠธ ์ƒ์œ„ ์š”์†Œ์—์„œ ๊ฐ์ง€(์ด๋ฒคํŠธ ๋ฒ„๋ธ”๋ง)
document.addEventListener("click", (e) => {
  if (e.target.matches("div")) {
    console.log("hi");
  }
});

addGlobalEventListener("click", "div", (e) => {
  console.log("hi");
});

function addGlobalEventListener(type, selector, callback) {
  document.addEventListener(type, (e) => {
    if (e.target.matches(selector)) callback(e);
  });
}

Reference

DOM Event | JS Info

Event Bubbling & Capturing

Last updated