jQuery: passThrough

more at: http://stackoverflow.com/a/9385266/1250044

by Yannick Albert

HTML

<div class="overlay"></div>
<div class="box"></div>

CSS

.overlay {
    position: absolute;
    width: 200px;
    height: 100%;
    top: 0;
    background-color: red;
    opacity: 0.5;
}

.box {
    width: 100px;
    height: 100px;
    margin-left: 150px;
    background: indigo;
}

.active {
    background: cyan;
}

JavaScript

$.fn.passThrough = function (target) {
    var $target = $(target);
    return this.each(function () {
        var style = this.style;
        if ('pointerEvents' in style) {
            style.pointerEvents = style.userSelect = style.touchCallout = 'none';
        } else {
            $(this).on('click mousedown mouseup mouseenter mouseleave mousemove touchstart touchend touchcancel touchmove', function (e) {
                var touch = /touch/.test(e.type) ? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0] : e;
                $target.each(function() {
                    var rect = this.getBoundingClientRect();
                    if (e.pageX > rect.left && e.pageX < rect.right &&
                        e.pageY > rect.top && e.pageY < rect.bottom)
                        $(this).trigger(e.type);
                });
            });
        }
    });
};

$('.overlay').passThrough('.box');
$('.box').hover(function(){
    $(this).toggleClass('active');
});