'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?



Solution 1:[1]

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
});

Solution 2:[2]

This works without jQuery

<div class="outerElement">
    <div class="attachment">Hello</div>
</div>

<script type="text/javascript">
document.getElementsByClassName('outerElement').onclick = function(){

    alert('You clicked on parent');

}
document.getElementsByClassName('attachment').onclick = function(){

    event.stopPropagation();
    alert('You clicked on child');

}
</script>

Solution 3:[3]

Simply setting onclick="event.stopPropagation();" on the children will do.

Solution 4:[4]

I'm not sure if you can prevent the event from firing when the attachment item is clicked but you can certainly filter for it

$('.outerElement').click(function() {
  if ($(this).hasClass('attachment')) {
    return;
  }
  // Handle event
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 NicB
Solution 3 Johann Burgess
Solution 4 JaredPar