stopPropagation and preventDefault jQuery Methods

Simple demo of stopPropagation() and preventDefault() jQuery methods. Often these two methods are used together. And, often their function and use is confused or used when not needed thanks to copy and paste.

stopPropagation()

stopPropagation() prevents events that are attached to elements from moving up the DOM to the parent. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing. jQuery docs on stopPropagation().

<div id="parentDiv">
    <h1>The Parent Div</h1>
    <p><a href="http://api.jquery.com" id="childLink">Child Link</a></p>
</div>
$("#parentDiv").click(function() {
    alert("Parent div click function called.");
});

$("#childLink").click(function(e) {
    // e = event
    e.stopPropagation();
    // click on this link will cause ONLY child to fire
    alert("Child link click function called.");
});

preventDefault()

preventDefault() prevents the default behavior of an element. It prevents a FORM from submitting, a link from loading a page, or a button from doing what it does. If an element does not have a default behavior for the method attached to it by jQuery then it is not needed. For example, if a click event is attached to a DIV element, preventDefault() is not needed. What is the default click behavior of a simple DIV element? Nothing. jQuery docs on preventDefault().

<div id="parentDiv">
    <h1>The Parent Div</h1>
    <p><a href="http://api.jquery.com" id="childLink">Child Link</a></p>
</div>
$("#parentDiv").click(function() {
    // preventDefault() not needed in this case on the DIV
    alert("Parent div click function called.");
});

$("#childLink").click(function(e) { 
    // e = event
    e.stopPropagation();
    // click on this link will cause ONLY child to fire
    e.preventDefault();
    // link will not proceed to HREF url
    alert("Child link click function called.");
});

Demo

Posted in jquery, Web development. Tags: . Permalink. Both comments and trackbacks are closed.