jQuery - Using event click on parent and child div

1

I have two div. I'm trying to do the following. When I click on the parent div it should return the alert. But when I click on the child div nothing should happen. I tried something down, but I did not succeed.

I know it did not work because it is calling two events, the parent div, and the child div. But I do not know how to prevent it from calling the parent div event by clicking on the child div.

Do you have any simple way to do this 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><divclass="pai">
  Pai
  <div class="filho">Filho</div>
</div>
    
asked by anonymous 26.08.2016 / 19:00

1 answer

3

If I understand correctly that the event does not propagate to the child but that it triggers when clicking the father (click anywhere of the father except the son). You must give a e.stopPropagation(); to the child 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><divclass="pai">
  Pai
  <div class="filho">Filho</div>
</div>
    
26.08.2016 / 19:05