event.preventDetault() method:
event.preventDetault() method stops default action of the element, e.g. In preventDefault() method when click on element like <a> its stops the link to executed or on Form submit button click stop form to be submitted.
HTML:
<div id=”div-element”>
<a id=”anchor-element” href=”http://www.xyz.com” target=”_blank”>
xyz.com
</a>
</div>
CODE:
$(“document”).ready(function(){
$(“#anchor-element”).click(function(event){
event.preventDefault();
});
});
event.stopPropagation() method:
event.stopPropagation() method stops event handlers to being executed (i.e. click(), hover(), mouseover(), mouseout()…) of the parent elements.
HTML:
<div id=”div-element”>
<span id=”span-element”>
SPAN Tag
</span>
</div>
CODE:
$(“document”).ready(function(){
$(“#div-element”).click(function(){
alert(“Parent DIV Element”);
});
$(“#anchor-element”).click(function(event){
event.stopPropagation();
alert(“Child SPAN Element”);
});
});
In the above example <div> is a parent element of <span> tag. When you click on SPAN Tag text because of event.stopPropagation() method on span tag here alert message shown “Child SPAN Element” but not div tag alert message which is “Parent DIV Element”.