Home > UI/UX Development > jQuery > jQuery: Difference between event.preventDefault() method and event.stopPropagation() method

jQuery: Difference between event.preventDefault() method and event.stopPropagation() method

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”.

This Article is TAGGED in , , . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">