yoozer8 yoozer8 - 4 months ago 6
Javascript Question

Trigger child element's onclick event, but not parent's

I've got some nested elements, each with an onclick event. In most cases, I want both events to fire when the user clicks the child (both parent and child events are triggered - default behavior). However, there is at least one case where I want to trigger the child's onclick event (from javascript, not a user's click), but not the parent's. How can I prevent this from triggering the parent event?

enter image description here

What I was is:

User clicks A: A's onclick fires.

User clicks B: B's onclick fires, A's onclick also fires

Manually trigger B's click: B fires, A does not (this one is the problem)

Jon Jon
Answer

Use triggerHandler on the child; this will not let the event propagate through the DOM:

Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Comments