Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop click event propagation of all children

How to stop the click event propagation of all children elements:

<div (click)="openModal()">
    <span>Click in this element open the modal</span>
    <li>Click in this element open the modal too</li>
    <p>Click in this element open the modal too</p>
    <input type="button">Click in this element open the modal too</input>
</div>

I want to open the modal only with the div element. Is there a way to do it?

like image 749
in3pi2 Avatar asked Feb 08 '17 03:02

in3pi2


People also ask

How do you stop event propagation from parent to child?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

How will you prevent event from being propagated?

stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.

How do you stop event propagation in react?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.


Video Answer


1 Answers

If you want to conditionally execute logic only when the parent div element is clicked (and not when the event propagates when clicking on a child element), then you could check to see if the event's currentTarget property is equal to the target property.

  • The currentTarget property always refers to the element that the event is bound to. In this case, the (click) event is bound to the div element.
  • The event.target property always refers to the element that dispatched the event.

Therefore, if you only want to filter out instances where a child element is clicked and you want to essentially filter out propagated events, then you can check to see if $event.currentTarget is equal to $event.target:

public openModal ($event) {
  if ($event.currentTarget === $event.target) {
    // Clicked on the parent `div` element with the
    // click event binding `(click)="openModal($event)"`
    console.log('Clicked the parent, not the child.');
  }
}
<div (click)="openModal($event)">
  <span>...</span>
  <p>...</p>
</div>
like image 155
Josh Crozier Avatar answered Oct 21 '22 07:10

Josh Crozier