stopPropagation
prevents further propagation of the current event in the capturing and bubbling phases.
preventDefault
prevents the default action the browser makes on that event.
Examples
preventDefault
$("#but").click(function (event) { event.preventDefault() }) $("#foo").click(function () { alert("parent click event fired!") })
<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>
stopPropagation
$("#but").click(function (event) { event.stopPropagation() }) $("#foo").click(function () { alert("parent click event fired!") })
<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>
With stopPropagation
, only the button
‘s click handler is called while the div
‘s click handler never fires.
Where as if you use preventDefault
, only the browser’s default action is stopped but the div’s click handler still fires.
Below are some docs on the DOM event properties and methods from MDN:
For IE9 and FF you can just use preventDefault & stopPropagation.
To support IE8 and lower replace stopPropagation
with cancelBubble
and replace preventDefault
with returnValue