JQuery, Binding on nested element
In this simple example, there is a nasty bug
<html>
<head>
<script src=”http://code.jquery.com/jquery-1.11.0.min.js”></script>
</head>
<body>
<div id=”outer” style=”background:red; width:400px; height:200px”>
<div id=”inner” style=”background:blue; width:200px; height:100px”>
</div>
</div>
<script>
$(init);
function init()
{
$(“#outer”).bind(“click”, outer_click);
$(“#inner”).bind(“click”, inner_click);
}
function outer_click(event){
alert(“outer click”);
}
function inner_click(event){
alert(“inner click”);
}
</script>
</body>
</html>
If you click on the blue square, then you get two alerts, one for the inner element, and one for the outer element.
The solution is to stop event bubbling, by including this on the inner_click
event.stopPropagation();