jqueryhtmlcsseventsclick-through

How can I get 3 divs overlayed to allow click-through that fires all underlying div's event handlers?


I have 3 divs overlayed like so:

<div id="div1" style="height: 500px; width: 500px; position:absolute; z-index: 1"></div>
<div id="div2" style="height: 500px; width: 500px; position:absolute; z-index: 2"></div>
<div id="div3" style="height: 500px; width: 500px; position:absolute; z-index: 3"></div>

All of them have on.click event handlers that pop up different messages

Is it possible that when clicking one, no matter which one is on top, it allows all underlying divs with click through (tried "pointer events: none" but that disables all functionality) to fire their respesctive event handlers? Say that I click on div 3 and div 2 and 3 fire their event handlers as well. Also, I don't want hardcoded solutions like:

$('#div3').on('click',function() {
   // trigger div 1 and 2 events manually
})

The problem with pointer events: none is that whoever has it, won't trigger it's event handler like I want it, any way to fix that?


Solution

  • I'm not sure if this solution is too "hardcoded" for you, but it will detect any elements behind the front element and trigger their click handlers (if the mouse click was also located above that element)

    $('#div3').click(function(e) {
    $(this).hide();
    var elements = [];
    var element;
    var count = 0;
    element = $(document.elementFromPoint(e.clientX,e.clientY));
    while (element.prop("tagName") != "HTML" && count < 15) {
        elements.push(element);
        $(element).hide();
        element = $(document.elementFromPoint(e.clientX,e.clientY));
        count++;
    }
    $(elements).each(function() {
        $(this).trigger("click");
        $(this).show();
    });
    $(this).show();
    });
    

    Fiddle: http://jsfiddle.net/13jLrarp/3/

    The count is there to make sure it doesn't get stuck in an infinite loop (just in case) though it technically isn't required

    In the fiddle, clicking the green box will make the red box grow horizontally and clicking the blue box will make the red box grow vertically. Clicking where they overlap makes the red box grow both ways. Notice that using z-index the red box is placed on top of the other two