Persist Click Layers
Persist mouse events through overlay mask.
by dixalex
HTML
<div id="container">
<div class="box" style="position:absolute; top: 25px; left: 25px;"></div>
<div class="box" style="position:absolute; top: 50px; left: 125px;"></div>
<div class="box" style="position:absolute; top: 100px; left: 25px;"></div>
<div class="box" style="position:absolute; top: 125px; left: 180px;"></div>
<div class="box" style="position:absolute; top: 225px; left: 25px;"></div>
<div class="box" style="position:absolute; top: 185px; left: 125px;"></div>
<div id="shield" style="position: absolute; top: 0px; background-color: grey; opacity: 0.5;"></div>
</div>
<div id="controls">
<input type="checkbox" checked="checked">Pass pointer events through</input>
Try clicking
</div>
CSS
body {
background-color: #000;
}
.box {
width: 50px;
height: 50px;
border: 1px solid white
}
.highlight {
background-color: yellow;
}
#controls {
position: absolute;
top: 300px;
color: white;
}
#shield {
height: 290px;
width: 275px;
}
#container {
background-color: #ACE;
border: solid 5px yellow;
}
JavaScript
//http://jsbin.com/uhuto/1586/edit?html,js,output
//https://hacks.mozilla.org/2009/12/pointer-events-for-html-in-firefox-3-6/
//http://www.vinylfox.com/forwarding-mouse-events-through-layers/
//Absolutely position the last element to force it to be a mask.
var dthen = new Date();
function passThrough(e) {
$(".box").each(function() {
// check if clicked point (taken from event) is inside element
var mouseX = e.pageX;
var mouseY = e.pageY;
var offset = $(this).offset();
var width = $(this).width();
var height = $(this).height();
if (mouseX > offset.left && mouseX < offset.left + width && mouseY > offset.top && mouseY < offset.top + height) {
$(this).click(); // force click event
console.log("(X: " + mouseX + ", Y: " + mouseY + ") Timestamp: " + dthen + ".");
}
});
}
$("#shield").click(passThrough);
var doPassThrough = true;
$('input').click(function() {
doPassThrough = !doPassThrough;
if (doPassThrough) {
$("#shield").click(passThrough);
} else {
$('#shield').off('click', passThrough);
}
});