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 –

    <span>Click Here</span>

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.
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() 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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s