Outer element's events overriding inner element's events – jQuery

When an element is placed in another element (usually a container like DIV,  SPAN etc), and if both inner and outer elements have an event (like click), the outer element’s event will override inner element’s event, hindering the functionality of inner element and obstruct it from executing.
When you handle the elements with ID, events of the container element(s) will also gets executed i.e., Event Bubbling will happen.
Let’s see this case with a simple example –
Markup:

<div>
    <span>Click Here</span>
</div>

jQuery Code:

$(document).ready(function() {
    $("#MyDiv").click(function() {
        alert("Clicked on DIV");
    });
    $("#MySpan").click(function() {
        alert("Clicked on SPAN");
    });
});

In this case, if you click on ‘Click Here’, it will invoke the click function of DIV as the DIV is overriding the SPAN click event.
 
Work-Around:
Here is the code that works –

$(document).ready(function() {
    $("div.MyDiv").click(function() {
        alert("Clicked on DIV");
    });
    $('div.MyDiv span').click(function(e) {
        alert('Clicked on SPAN');
        e.stopPropagation();
    });   
});

e.stopPropagation() prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Here is its implementation on jsFiddle –

Hope this helps!

Leave a Comment

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