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
Last updated