Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling a click event from the child of a parent div

I am trying to add a on click event to a div with a class parent. Now inside that div I have a div with class child that has its own click event.

How can I manage to disable the click event of the parent function for that child element in order to execute the function of child element itself?

I have tried using pointer-event:none; but it does not seem to be working. I have wrote a jsfiddle for better understanding.

https://jsfiddle.net/arq1epbs/

$(document).on('click', '.parent', function() {
  var url = $(this).attr("data-url")
  document.location.href = url
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent" data-url="www.google.com">
  Im the parent
  <div class="child">
    im the child and I don't want to go to Google
  </div>
</div>

Thanks for all the help in advance!

like image 991
ashes999 Avatar asked Sep 11 '25 12:09

ashes999


2 Answers

You can use stopPropagation():

 $(document).on('click', '.parent', function () {
    var url = $(this).attr("data-url")
    document.location.href = url 
});
 $(document).on('click', '.child', function (e) {
 e.stopPropagation();
});

As it's not working in the Stack Snippet, here a Fiddle For reference: stopPropagation()

like image 156
matthias_h Avatar answered Sep 14 '25 03:09

matthias_h


You can simply call event.stopPropagation() inside child click event, to prevent the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the child click event like:

$(document).on('click', '.parent', function() {
  //var url = $(this).attr("data-url")
  //document.location.href = url
  console.log('Parent Clicked');
});

$(document).on('click', '.child', function(event) {
  event.stopPropagation();
  console.clear();
  console.log('Child Clicked');
});
.parent{background:#99c0c3;width:350px;height:120px;position:relative}
.child{background:#ffde99;width:300px;height:50%;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent" data-url="www.google.com">
  Im the parent
  <div class="child">
    im the child and I don't want to go to Google
  </div>
</div>
like image 31
palaѕн Avatar answered Sep 14 '25 03:09

palaѕн