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

[JavaScript] ์ด๋ฒคํŠธ ๋ฒ„๋ธ”๋ง(Event Bubbling) + e.stopPropagation()

by rindev 2021. 9. 17.

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

 

๐Ÿค” ๋ฒ„๋ธ”๋ง์ด๋ž€?

ํŠน์ • ํ™”๋ฉด ์š”์†Œ์—์„œ ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, ํ•ด๋‹น ์ด๋ฒคํŠธ๊ฐ€ ๋” ์ƒ์œ„์˜ ํ™”๋ฉด ์š”์†Œ๋“ค๋กœ ์ „๋‹ฌ๋˜๋Š” ํŠน์„ฑ (propagate up)

<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");
});

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

์ด๋ฒคํŠธ ํ”Œ๋กœ์šฐ์˜ default ๊ฐ’์€ Bubble ์ด๋ฏ€๋กœ,

divbodyhtml ์ˆœ์œผ๋กœ ์ด๋ฒคํŠธ๊ฐ€ ์ง„ํ–‰๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

๐Ÿ– ๋ฒ„๋ธ”๋ง์„ ๋ง‰๋Š” e.stopPropagation()

  • e.stopPropagation() : ๋ถ€๋ชจ ํƒœ๊ทธ๋กœ์˜ ์ด๋ฒคํŠธ ์ „ํŒŒ๋ฅผ ์ค‘์ง€์‹œํ‚ด (๋‚ด ๋’ค๋กœ ๋‹ค ๋ฉˆ์ถฐโœ‹!!!)

html์€ capture๋กœ ์„ค์ •๋ผ์žˆ๊ณ , body๋Š” bubble๋กœ ์„ค์ • ๋ผ ์žˆ๋Š” ์ƒํ™ฉ์ด๋ผ๋ฉด

( Capture → Target → Bubble ์ˆœ์„œ๋Š” ๊ฐœ๋ฐœ์ž๊ฐ€ ์–ด๋–ป๊ฒŒ ํ•  ์ˆ˜๊ฐ€ ์—†์œผ๋ฏ€๋กœ! )

 

โ‘ html → (body : ๋‚˜๋Š” ๋‚˜์ค‘์— ์‹คํ–‰ ํ•ด์•ผ์ง€) → โ‘กdiv ์ˆœ์„œ๋กœ ์‹คํ–‰๋œ๋‹ค. (body : ์ด์ œ ๋‚ด ์ฐจ๋ก€์ธ๋ฐ ์™œ ์•ˆ์‹œ์ผœ์ค˜...ใ… ใ… )

div์—์„œ e.stopPropagation()์„ ํ–ˆ์œผ๋ฏ€๋กœ ๋ฒ„๋ธ”๋ง์„ ๋ฐฉ์ง€ํ•ด์„œ body๋Š” ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค!

 

const html = document.documentElement;
const body = document.body;
const div = document.querySelector("div");

div.addEventListener("click", function (e) {
	console.log("div");
	e.stopPropagation(); //๋ถ€๋ชจ ํƒœ๊ทธ๋กœ์˜ ์ด๋ฒคํŠธ ์ „ํŒŒ ์ค‘์ง€ ์„ ์–ธ
});

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

html.addEventListener("click", function () {
	console.log("html");
}, true); //html์€ Capture๋กœ ์ง€์ •๋จ

 

 

๐Ÿ‘€ ์ฐธ๊ณ 

 

 

๋Œ“๊ธ€