Search code examples
jqueryevent-bubblingpreventdefaultstoppropagation

Shouldn't returning false prevent jQuery on() from bubbling up?


According to the jQuery docs

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }. So, $("a.disabled").on("click", false); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

So when I create a click event:

$('#sidebar').on("click", ".toggle", function() {
    $(this).parents("p").next("ul").toggle(400);
    return false;
});

I would expect the click to not register since it would not have a chance to propagate from .toggle to #sidebar

The only explanation I've come up with would be that if this was allowed to happen it would make the on() function fairly pointless, so perhaps it's bypassed in this case?

What rules does on() follow as far as bubbling?


Solution

  • Actually, the handler is attached to the element #sidebar, not to the .toggle elements.

    So when you click on an inner element, the event bubbles up until it reaches `#sidebar' and then only the handler is executed. Returning false in the handler, will then stop the propagation further up.


    The documentation for .on() mentions this through an example:

    In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

    $("#dataTable tbody tr").on("click", function(event){
        alert($(this).text());
    });
    

    A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

    $("#dataTable tbody").on("click", "tr", function(event){
        alert($(this).text());
    });