본문 바로가기

Frontend/jQuery

JS jQuery (part. 26) - 기본 이벤트와 이벤트 전달

  • preventDefault( ) : 기본 이벤트를 제거한다
  • stopPropagation( ) : 이벤트 전달을 제거한다
<body>
    <h1>
        <a href="https://www.naver.com/">네이버</a>
    </h1>
</body>

 

a 태그와 h1 태그에 이벤트를 연결한다 하지만 a 태그의 기본 이벤트가 실행되어서 h1 태그의 이벤트가 소용이 없는 상황이 된다

 

$(function () {
  $('a').click(function (event) {
    $(this).css('background-color', 'blue');
	event.preventDefault();
  });

  $('h1').click(function () {
    $(this).css('background-color', 'red');
  });
});

 

코드를 실행하면 a 태그 클릭시  a 태그 이외에 h1 태그에도 이벤트 전달이 일어난다

이벤트 전달을 막으려면 이벤트 객체의 stopPropagation( ) 메서드를 사용한다

 

$(function () {
  $('a').click(function (event) {
    $(this).css('background-color', 'blue');
    event.stopPropagation();
    event.preventDefault();
  });

  $('h1').click(function () {
    $(this).css('background-color', 'red');
  });
});

a 태그를 클릭해도 이벤트 전달이 일어나지 않는다

 

stopPropagation( ) 메서드와 preventDefault( ) 메서드를 함께 사용하는 경우가 많으므로

jQuery에서는 간단하게 return false를 사용해서 두 가지를 함께 적용하는 것으로 인식한다

 

$(function () {
  $('a').click(function (event) {
    $(this).css('background-color', 'blue');
    return false;
  });

  $('h1').click(function () {
    $(this).css('background-color', 'red');
  });
});

 

기존 자바스크립트는 return false를 사용하면 기본 이벤트만 제거된다는 점을 주의