I have an absolute positioned image on top of another image.
Now when I bind a click event to the image in the background and click the overlaying image the click event does not bubble up to the background image as expected.
Meanwhile it does bubble further up to the underlying div.
<div class="container">
<img src="http://dummyimage.com/600x400/000/fff&text=Background" id="bg" />
<img src="http://dummyimage.com/100x100/ff00ff/000000&text=Overlay" id="overlay" />
</div>
$(function(){
$("#bg").on("click", function(){
alert("Click on background");
});
$("#overlay").on("click", function(){
alert("Click on overlay - should bubble to background and container");
});
$(".container").on("click", function(){
alert("Click on either overlay or background which bubbled through to the container");
});
});
jsfiddle here: http://jsfiddle.net/V9dkD/2/
I really do not understand why this happens.
How can I make the click on the top image bubble up to the background image without changing the html structure?
You will have to trigger a click on the other image. When it comes to mouse events, it's the structure and not the position that matters.
$(function(){
$("#bg").on("click", function(){
alert("Click on background");
});
$("#overlay").on("click", function(){
alert("Click on overlay - should bubble to background and container");
$("#bg").trigger('click');
});
$(".container").on("click", function(){
alert("Click on either overlay or background which bubbled through to the container");
});
});
Here is a forked fiddle. Note that this will cause the .container
click event handler to trigger twice. You can prevent this with return false
in the bg
handler. You will just have to make some adjustments depending on your actual use case.