Mossawi
Mossawi

Reputation: 911

How to make only the parent div clickable?

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?

Upvotes: 1

Views: 1039

Answers (2)

Omidam81
Omidam81

Reputation: 1917

$(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>

Upvotes: 3

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

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>

Upvotes: 4

Related Questions