1

Is there anyway to stop the parent click event going off when a specific child element is touched.

For example in this example I want to log outer which clicking blue and inner when clicking red.

How do I stop the outer event firing on inner div?

$("#outer").click(function(){
  console.log("outer");                 
});

//tried these but doesnt do anything
$("#inner").off();
$("#inner").unbind();

$("#inner").click(function(e){
  console.log("inner");                 
});
#outer{
  background-color: blue;
  width: 500px;
  height: 700px;
}
#inner{
  background-color: red;
  width: 100%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="outer">
  <div id="inner"></div>
</div>
Guerrilla
  • 13,375
  • 31
  • 109
  • 210

1 Answers1

0

You can call stopPropagation to prevent the event from bubbling up and triggering the listener on #outer:

$("#outer").click(function(){
  console.log("outer");                 
});
$("#inner").click(function(e){
  e.stopPropagation();
  console.log("inner");                 
});
#outer{
  background-color: blue;
  width: 500px;
  height: 700px;
}
#inner{
  background-color: red;
  width: 100%;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<div id="outer">
  <div id="inner"></div>
</div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320