1

As my title explains, how can I make only the parent-div clickable?

HTML

<div id="canvas" onclick="closeCanvas()">
    <img src="image.png" />
</div>

JQUERY

function closeCanvas(){
    $("#canvas").fadeOut(300);
}

My issue is that when I click the "image", the function closeCanvas() is also trigged. How can I make only the parent, #canvas, triggerable?

Mossawi
  • 871
  • 2
  • 10
  • 17
  • 1
    Add this to `img`, `onclick="event.stopPropagation()"` – Tushar Oct 17 '15 at 19:57
  • Also see `event bubbling`. Check [What is event bubbling and capturing](http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing) – Tushar Oct 17 '15 at 20:01

2 Answers2

4

Add StopPropagation to img that mean clicking the img will not pass the click event to the parent div:

<div id="canvas" onclick="closeCanvas()">
   <img src="image.png" onClick="event.stopPropagation()" />
</div>
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51
3

$(document).ready(function(){
  $('canvas').click(function(e){
      console.log(e);  
  });

  
});

function closeCanvas(event){
  if(event.target.id== "canvas")
    $("#canvas").fadeOut(300);
}
#canvas{
  height:100px;
  width:100px;
  background-color:red;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="canvas" onclick="closeCanvas(event)">
    <img src="image.png" />
</div>
Omidam81
  • 1,887
  • 12
  • 20