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

Asked

Viewed 307 times

0

I have a div and inside it has several other elements (img, span, etc.). What I need to do is only when I click on div father the prompt open javascript, if click another element (child, those inside) nothing happens.

The problem is that when I click on any element inside the div father, he does the function I gave to 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()
                   );
      });

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

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>
<div class="taggd" id="pai">
  Pai
  <p id="filho">Filho</p>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.