Web/DOMBrowser

Difference between event.stopPropagation and event.preventDefault

데먕 2019. 9. 28. 16:25

1. Overview

Let's distribute the difference between event.stopPropagation and event.preventDefault in DOM Event fine-grained.

 

2. Description

  • stopPropagation

stops the event from bubbling up the event chain.

 

  • preventDefault 

prevents the default action the browser makes on that event.

 

3. Examples

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
$("#but").click(function (event) {
  //using preventDefault, only the browser's default action is stopped but the div's click handler still fires.  
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})


$("#but").click(function (event) {
  // With stopPropagation, only the button's click handler is called while the div's click handler never fires.
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})

 

 

4. References

https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault