본문 바로가기

UI

stopPropagation()과 preventDefault() 의 차이

이벤트를 막기 위해 쓰는 stopPropagation()과 preventDefault() 의 차이

사용자가 발생한 이벤트를 막느냐, 기본 이벤트를 막느냐의 차이로 구분 할 수 있다.



<div class="wrapper">
<a href="https://www.google.co.kr">
<span><img src="img.jpg" alt="product"></span>
</a>
</div>

<script>
$('.wrapper span').on('click', function(){
alert('span 클릭했어요');
});

$('.wrapper img').on('click', function(){
alert('img 클릭했어요');
});
</script>


alert= img 클릭했어요 > alert= span 클릭했어요 > https://www.google.co.kr 순으로 이동




<div class="wrapper">
<a href="https://www.google.co.kr">
<span><img src="img.jpg" alt="product"></span>
</a>
</div>

<script>
$('.wrapper span').on('click', function(e){
e.stopPropagation();
alert('span 클릭했어요');
});

$('.wrapper img').on('click', function(t){
t.stopPropagation();
alert('img 클릭했어요');
});
</script>

alert= img 클릭했어요 > https://www.google.co.kr 순으로 이동. 

사용자가 발생한 이벤트 막힘.




<div class="wrapper">
<a href="https://www.google.co.kr">
<span><img src="ㅑㅡ.jpg" alt="product"></span>
</a>
</div>

<script>
$('.wrapper span').on('click', function(e){
e.preventDefault();
alert('span 클릭했어요');
});

$('.wrapper img').on('click', function(t){
t.preventDefault();
alert('img 클릭했어요');
});
</script>

alert= img 클릭했어요 > alert= span 클릭했어요 순으로 이동.

기본 이밴트 막힘.