javascript - What's the difference between event.stopPropagation and event.preventDefault? -
they seem doing same thing... 1 modern , 1 old? or supported different browsers?
when handle events myself (without framework) check both , execute both if present. (i return false
, have feeling doesn't work events attached node.addeventlistener
).
so why both? should keep checking both? or there difference?
(i know, lot of questions, they're sort of same =))
stoppropagation
stops event bubbling event chain.
preventdefault
prevents default action browser makes on event.
let's have
<div id="foo"> <button id="but" /> </div> $("#foo").click(function() { // mouse click on div }); $("#but").click(function(ev) { // mouse click on button ev.stoppropagation(); });
example
$("#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>
$("#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
buttons click handler called , divs click handler never fires.
where if preventdefault
browsers default action stopped div's click handler still fires.
below docs on dom event objects mdn
, msdn
msdn:
mdn:
for ie9 , ff can use preventdefault & stoppropagation.
to support ie8 , lower replace stoppropagation
cancelbubble
, replace preventdefault
returnvalue
Comments
Post a Comment