Only open prompt if you click the parent element and not the child element

0

I have div and inside it has several other elements (img, span, etc.). What I need to do is that only when I click on div parent the prompt of javascript opens, if you click on another element (child, the ones inside) nothing happens.

The problem is that when I click on any element that is inside the% co_of% parent, it does the function I gave the parent element, but I'm clicking on the child element.

$(document).on('click', '.taggd', function (e) {

          let imgWidth  = $("div.taggd").width();
          let imgHeight = $("div.taggd").height();

          let left = Math.floor(((e.pageX - $(this).offset().left) * 100)/imgWidth),
              top  = Math.floor(((e.pageY - $(this).offset().top) * 100)/imgHeight);

          let texto = prompt('O que deseja exibir ?');

          taggd.addTag(
                   Taggd.Tag.createFromObject({
                        position: { x: left/100, y: top/100 },
                        text: texto,
                    }).show()
                   );
      });

.taggd is the parent element and when clicked anywhere on this div it has to do this function that is inside. But inside that div has other elements that will have other functions, but every time I click on the child element, it is executing the above code.

    
asked by anonymous 05.05.2017 / 17:29

1 answer

1

There are two options:

  • add a e.stopPropagation(); to prevent the event from spreading.

document.addEventListener('click', function(e) {
  if (e.target.nodeType == 1 && e.target.classList.contains('taggd')) {
    e.stopPropagation();
    console.log('click no pai');
  } else {
    console.log('click no filho');
  }
}, true);
<div class="taggd" id="pai">
  Pai
  <p id="filho">Filho</p>
</div>
  • Compare e.target === this :

$(document).on('click', '.taggd', function(e) {
  if (e.target == this) console.log('Pai');
  else console.log('Filho');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="taggd" id="pai">
  Pai
  <p id="filho">Filho</p>
</div>
    
05.05.2017 / 17:43