jQuery - Using event click on div father and son

Asked

Viewed 880 times

1

I have two div. I am trying to do the following. When I click on the father div it should return the Alert. But when I click on the div child nothing should happen. I tried something below but did not succeed.

I know it didn’t work because he’s calling two events, the father’s div, and the son’s div. But I don’t know how to stop him from calling the father div event by clicking on the son div.

You’ve found some simple way to do it with jQuery?

$('.pai, .filho').click(function(){
  
   if($(this).attr('class') == 'pai') { 
     alert('teste');
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="pai">
  Pai
  <div class="filho">Filho</div>
</div>

1 answer

3


If I understand correctly, you want the event not to propagate for the child but to shoot by clicking on the father (click on any place of the father except the son). Has to give a e.stopPropagation(); to the son also in the event click:

$(".pai").on('click', function(){
    alert('teste');
});
$(".filho").on('click', function(e) {
   e.stopPropagation();
   console.log('não vou fazer nada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="pai">
  Pai
  <div class="filho">Filho</div>
</div>

  • Oops! That’s exactly what I was looking for. Thanks! ;)

  • I’m glad you solved @Alan. You’re welcome

Browser other questions tagged

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