jQuery Prevent Event Bubbling


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

jQuery Prevent Event Bubbling

Here we look at how to prevent events bubbling using jQuery.

A little while ago I was looking at how to stop an event bubbling up using Javascript. I though it would be really quick to find out how to do it, but in the event my searches took a little while longer than I thought it would do, but I found the answer in the end. So what a nice a surprise it was today to find out that I could have done this using jQuery! So I had to get a quick mention on the high-flying.co.uk website.

So let's say we have an outer and an inner div, and both divs have event handlers wired up for clicking in the div:


<div id="outerClickMe">
    Outer Click Me
    <div id="clickMe">
        Click Me
    </div>
</div>



<script type="text/javascript">

    $(document).ready(function () {
        $('#clickMe').bind("click", function (event) {
            $('#clickMe').after("<br />and some extra");
        });

        $('#outerClickMe').bind("click", function (event) {
            $('#outerClickMe').before("Some before<br />");
        });
    });

</script>


So what happens here is that if we click the outer div, the outer div click event fires, but if we click the inner div, the inner div's click event fires, but then additionally after this the event bubbles up to the outer div and caused the outer div's click event to fire too! So you may not want that to happen in certain cases, so:

jQuery Prevent Event Bubbling

So using jQuery, all you need to stop the event bubbling up is the event.stopPropagation() method call.


event.stopPropagation();

So in the previous example, the following code stops the inner div's click event bubbling up to the outer div's event handler:


<script type="text/javascript">

    $(document).ready(function () {
        $('#clickMe').bind("click", function (event) {
            $('#clickMe').after("<br />and some extra");
                event.stopPropagation();
        });

        $('#outerClickMe').bind("click", function (event) {
            $('#outerClickMe').before("Some before<br />");
        });
    });

</script>