Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No onclick when child is clicked

I have the following html code:

<div class="outerElement">
    <div class="text">
     Lorem ipsum dolar sit amet
    </div>
    <div class="attachment">
      <!-- Image from youtube video here -->
    </div>
</div>

And I have a jQuery onclick event on the .outerElement however, I don't want the .outerElement onclick event to be called when I click on the attachment, is there some way to prevent this or to check which element is clicked?

like image 553
xorinzor Avatar asked May 11 '12 15:05

xorinzor


People also ask

How do I stop parent onclick event 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.


2 Answers

Use event.stopPropagation() on the child element.

$(".attachment").on("click", function(event){
  event.stopPropagation();
  console.log( "I was clicked, but my parent will not be." );
});

This prevents the event from bubbling up the DOM to the parent node.

Also part of the event object is the target member. This will tell you which element triggered the event to begin with. However, in this instance, stopPropagation appears to be the best solution.

$(".outerElement").on("click", function(event){
  console.log( event.target );
});
like image 98
Sampson Avatar answered Sep 25 '22 03:09

Sampson


I'm not sure what the performance implications of allowing the propagation from the child elements, but I solved this by comparing event.target and event.currentTarget:

onClick={(event) => {
  if (event.target === event.currentTarget) {
     console.log('Handle click');
  }
}}

This is React ^ More generalized javascript code would be:

$('.outerElement').click(function(event) {
  if (event.currentTarget !== event.target) {
    return;
  }
  // Handle event
});

You can also filter out specific element types like so:

$('.outerElement').click(function(event) {
  if (['input', 'select', 'option'].indexOf(event.target.localName) >= 0) {
    return;
  }
  // Handle event
});

like image 31
Conrad S Avatar answered Sep 25 '22 03:09

Conrad S