<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>Event.stopPropagation()</title>
</head>
<body>
<div>
<div id="out-box">
<button id="inner-box">innerbox</button>
</div>
</div>
</body>
<script>
document.querySelector("#out-box").addEventListener("click", () => {
console.log("out-box");
});
document.querySelector("#inner-box").addEventListener("click", () => {
console.log("inner-box");
});
</script>
</html>
#inner-box
를 클릭하면 부모 태그 #out-box
의 콘솔 창도 뜨는 것을 확인할 수 있다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>Event.stopPropagation()</title>
</head>
<body>
<div>
<div id="out-box">
<button id="inner-box">innerbox</button>
</div>
</div>
</body>
<script>
document.querySelector("#out-box").addEventListener("click", () => {
console.log("out-box");
});
document.querySelector("#inner-box").addEventListener("click", (e) => {
e.stopPropagation();
console.log("inner-box");
});
</script>
</html>
#inner-box
에 e.stopPropagation()
를 추가해 주면 부모 태그에 전달이 되지 않은 것을 알 수 있다.<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>Event.preventDefault()</title>
</head>
<body>
<div>
<a href="https://www.google.co.kr/" id="google">클릭 시 구글로 이동!</a>
</div>
</body>
<script>
document.querySelector("#google").addEventListener("click", (e) => {
e.preventDefault();
console.log("클릭함");
});
</script>
</html>
클릭 시 구글로 이동!
을 누르면 e.preventDefault()
때문에 구글로 이동하지 않고 콘솔 창만 뜨는 것을 확인할 수 있다.참고한 글
https://developer.mozilla.org/ko/docs/Web/API/Event/preventDefault
https://developer.mozilla.org/ko/docs/Web/API/Event/stopPropagation
https://ifuwanna.tistory.com/289