๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/JS

[JavaScript] ์ด๋ฒคํŠธ ์บก์ณ๋ง(Event Capturing)

by rindev 2021. 9. 23.

๐Ÿ“ƒ ์ด์–ด์ง€๋Š” ๊ธ€

 

๐Ÿค” ์บก์ณ๋ง์ด๋ž€?

์ด๋ฒคํŠธ ๋ฒ„๋ธ”๋ง๊ณผ ๋ฐ˜๋Œ€ ๋ฐฉํ–ฅ์œผ๋กœ ์ง„ํ–‰๋˜๋Š” ์ด๋ฒคํŠธ ์ „ํŒŒ ๋ฐฉ์‹

์ƒ์œ„์š”์†Œ → ํ•˜์œ„์š”์†Œ ์ด๋ฒคํŠธ ์ „๋‹ฌ์ด ์ง„ํ–‰ ๋จ (propagate down)

 

<html>
    <body>
        <div>ํด๋ฆญ</div>
    </body>
</html>
const html = document.documentElement;
const body = document.body;
const div = document.querySelector("div");

div.addEventListener("click", function () {
	console.log("div");
});

body.addEventListener("click", function () {
	console.log("body");
}, true);

html.addEventListener("click", function () {
	console.log("html");
}, true);

Capture์— true๋ฅผ ์ฃผ์—ˆ์œผ๋ฏ€๋กœ, htmlbodydiv ์ˆœ์œผ๋กœ ์ด๋ฒคํŠธ๊ฐ€ ์‹คํ–‰๋œ๋‹ค!

๋Œ“๊ธ€