JQuery on () and stopPropagation ()

I have a sidebar that slides to the left, adding content dynamically using get (). I want all clicks outside the panel to close it by calling a function. For other issues that 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 not make it work. I know that the on() function is triggered, but event.stopPropagation does not seem to work. Any tips?

+5
source share
1 answer

You cannot use stopPropagation() with delegated event handling (where the event handler is located at the parent).

This is because it is event propagation that does delegated event management in the first place, so by the time your event handler is called, the event is already propagating.

The order of events that occur in your code is: the distribution of events to the document object, then the event handler is called. Therefore, when you call event.stopPropagation() , it does nothing, because the event is already propagating.

If you want parent objects not to receive event propagation, you cannot use delegated event handling. You will have to assign event handlers directly to the objects themselves so that you can intercept the event before it propagates. If these are dynamically created objects, you will have to assign event handlers immediately after they are created.

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

+12
source

Source: https://habr.com/ru/post/944747/


All Articles