Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click on div that is on top of another div

Tags:

jquery

I have a problem with jQuery click when the selector is a for a div that is on top of another div as seen here..

the html

<div id="parent">
 <div id="child">
 </div>
</div>​

css

#parent{
 background-color:red;
 width:100px;
 height:100px;   
 position:relative;
}


#parent:hover #child {
 display:block;

}
#child{
 background-color:yellow;  
 width:10px;
 height:10px;  
 border: 1px solid black;
 position:absolute;
 display:none;
 bottom:0;
 right:0;
}

js

$("#parent").bind("click", function() {
    alert('you clicked on red');
});

$("#child").bind("click", function() {
    alert('you click on yellow');
});​

If you click on red #parent it gives the proper alert. If you click on yellow #child, it gives the yellow alert plus the red alert.

See the jsfiddle

Is there a way to fix this?

like image 814
Nick Ginanto Avatar asked Dec 09 '12 19:12

Nick Ginanto


1 Answers

Use jQuery's .stopPropagation()

$("#parent").bind("click", function() {
  alert('you clicked on red');
});

$("#child").bind("click", function(e) {
  e.stopPropagation();
  alert('you click on yellow');  
});​

http://jsfiddle.net/qTdkt/4/

like image 198
Sparky Avatar answered Oct 13 '22 06:10

Sparky