Event bubbling in jQuery

Let’s say we have the following document structure:

<body>
    <div>
        <button>Click</button>
    </div>
</body>

Thus, we have a three-level structure: at the highest level is the body element, below is the div element, and at the very bottom is the button element. Now let’s add click handlers for each successively:

$('button').bind('click', function(e){
        console.log('Event triggered element ' + e.target.tagName);
        console.log('Event handled for element ' + e.currentTarget.tagName);
    });
    $('div').bind('click', function(e){
        console.log('Event triggered element ' + e.target.tagName);
        console.log('Event handled for element ' + e.currentTarget.tagName);
    });
    $('body').bind('click', function(e){
        console.log('Event triggered element ' + e.target.tagName);
        console.log('Event handled for element ' + e.currentTarget.tagName);
    });
    

So, if we click on the button, then not only the button handler itself will work, but also the handlers above the underlying levels. Since clicking on the button is at the same time clicking on both the div element and the body element, since the button is inside them. The event will bubble up . That is, with each level up, the click event handlers will be looked up and, if present, they will be called.

However, we can disable the ascent. For example, we want only the button click handler to fire. In this case, we need to apply the method stopPropagation:

$('button').bind('click', function(e){
    console.log('Event triggered element ' + e.target.tagName);
    console.log('Event handled for element ' + e.currentTarget.tagName);
    e.stopPropagation();
});

Now handlers of higher levels will not be involved.