Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The only thing you really need to change is event handler for #overlay

$("#overlay").on("click", function(){  
    alert("Click on overlay - should bubble to background and container"); 
    $('#bg').trigger('click')
});

There are two cycles with events in js - capturing and bubbling, when it goes from root to via descendants to the element and back. Events are not propagated using positioning on the page, only DOM structure matters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top