ThisRestlessPilgrim
ThisRestlessPilgrim

Reputation: 541

Detect mousemove but let click events pass through

I have an overlay that I'm working on. I need clicks to pass through to the HTML elements underneath and for that I can use "pointer-events: none". However, I also need the overlay to detect mousemove events so that I can draw a massive crosshair over the position where the mouse cursor is. The problem is that setting "pointer-events" to "none" stops those mousemove events firing.

Suggestions?

Upvotes: 4

Views: 3443

Answers (2)

Miro
Miro

Reputation: 8660

In that case you need to get the mousemove events from the window, not the overlay.

$(window).mousemove( function(e){
    $('.v').css('left', e.clientX + 'px');
    $('.h').css('top', e.clientY + 'px');
});

Demo: http://jsfiddle.net/jze4acsd/1/

(Or if window is too broad for you, use the nearest parent of the elements you are interacting with - it would give you the same coordinates as the overlay)

Upvotes: 3

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

You can make a parent of the overlay which is the same size and can have a custom cross-hair mouse cursor via CSS and contains the elements you want to capture click events for. Then the child will still be able to capture click events.

HTML:

<div class="overlay-parent">
    <div class="below">This is the content below</div>
    <div class="overlay">This is the overlay</div>
</div>

CSS:

.overlay-parent, .overlay {
    top:0;
    bottom:0;
    left:0;
    right:0;
    position:absolute;
    cursor:crosshair;
}
.overlay {
    background-color:rgba(255, 0, 0, 0.5);
    pointer-events:none;
}
/* just to make it clear */
 .below {
    margin-top:100px;
}

Javascript:

$('.below').click(function () {
    console.log('clicked');
});

Demo: http://jsfiddle.net/7oLnnaxc/

Upvotes: -1

Related Questions