jQuery on() and stopPropagation()
Asked Answered
H

1

5

I have a side pane that slides in from the left, adding content dynamically with get(). I want all clicks outside the pane to cause it to close by triggering a function. Based on other questions I read, I came up with the following code.

$('html').click(function() {
    if (side_showing) {
        close_side();
    }
});

$(document).on("click", "#side", function(event) {  
    event.stopPropagation();
});

I can't seem to make it work. I know that the on() function is being triggered, but event.stopPropagation doesn't seem to be. Any tips?

Hepler answered 11/8, 2012 at 0:10 Comment(1)
Do you actually aware of the meaning of stopPropagation();? take a look javascripter.net/faq/eventbubbling.htm#demoHilliary
F
13

You can't use stopPropagation() with delegated event handling (where the event handler is on a parent).

That's because it is event propagation that makes delegated event handling work in the first place so by the time your event handler gets called, the event has already propagated.

The order of things happening in your code is: event propagation up to the document object, then your event handler gets called. So, when you call event.stopPropagation() it doesn't do anything because the event has already propagated.

If you need to keep parent objects from getting event propagation, then you can't use delegated event handling. You will have to assign event handlers directly to the objects themselves so you can intercept the event BEFORE it propagates. If these are dynamically created objects, then you will have to assign event handlers to them right after they are created.

The only other solution I know of is to put event handlers on the parent objects that you don't want to see these events and make sure those event handlers ignore the events if they originate on your #side object.

Finger answered 11/8, 2012 at 0:12 Comment(5)
@J4G - A couple options added to my answer.Finger
Can I use .click() after using .on("click") on an object?Hepler
@J4G - Sorry, I don't understand what you're asking.Finger
Does binding the click event to an object with .on() allow you to get the event with .click()?Hepler
@J4G - you can't call .click() to "get" an event. Binding an event handler allows you to install a callback function that will be called some time in the future, when a click event happens.Finger

© 2022 - 2024 — McMap. All rights reserved.