[JS] stopPropagation()와 preventDefault()의 차이점

sumin·2022년 10월 29일
0

Event.stopPropagation()

  • 하위 태그에서 발생한 이벤트를 상위 태그로 전파 되지 않도록(버블링) 막아주는 메서드
  • 버블링을 막아도 기본 이벤트 동작은 실행 된다.

event.stopPropagation() 없는 경우

<!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의 콘솔 창도 뜨는 것을 확인할 수 있다.

event.stopPropagation() 있는 경우

<!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-boxe.stopPropagation()를 추가해 주면 부모 태그에 전달이 되지 않은 것을 알 수 있다.

Event.preventDefault()

  • HTML태그에 기본으로 제공하는 동작을 실행하지 않도록 지정하는 메서드
<!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

0개의 댓글