I need to capture mouse events after a mousedown
event happens on an element.
On MDN setCapture, I don't see any mention about setCapture()
not being implement
in Chrome, but trying to run the example provided produces an Uncaugt TypeError
because e.target.setCapture
is basically undefined
in Chrome.
function init() {
var btn = document.getElementById("myButton");
btn.addEventListener("mousedown", mouseDown, false);
btn.addEventListener("mouseup", mouseUp, false);
}
function mouseDown(e) {
e.target.setCapture();
e.target.addEventListener("mousemove", mouseMoved, false);
}
function mouseUp(e) {
e.target.removeEventListener("mousemove", mouseMoved, false);
}
function mouseMoved(e) {
var output = document.getElementById("output");
output.innerHTML = "Position: " + e.clientX + ", " + e.clientY;
}
What is the equivalent API in Chrome?
I've finally come up with a complete ES2015 solution (explained on my blog) which captures the mouse events and effectively disables parasitic hover and pointer cursor changes while the mouse button is pressed.
Call captureMouseEvents(e)
from the event handler attached to the mousedown
event:
const EventListenerMode = {capture: true};
function preventGlobalMouseEvents () {
document.body.style['pointer-events'] = 'none';
}
function restoreGlobalMouseEvents () {
document.body.style['pointer-events'] = 'auto';
}
function mousemoveListener (e) {
e.stopPropagation ();
// do whatever is needed while the user is moving the cursor around
}
function mouseupListener (e) {
restoreGlobalMouseEvents ();
document.removeEventListener ('mouseup', mouseupListener, EventListenerMode);
document.removeEventListener ('mousemove', mousemoveListener, EventListenerMode);
e.stopPropagation ();
}
function captureMouseEvents (e) {
preventGlobalMouseEvents ();
document.addEventListener ('mouseup', mouseupListener, EventListenerMode);
document.addEventListener ('mousemove', mousemoveListener, EventListenerMode);
e.preventDefault ();
e.stopPropagation ();
}
Notice that the pointer-events: none
style prevents any component
receiving mouse events.
See the issue here, mentioning the fact that setCapture
is not supported. There is a suggested workaround towards the bottom of the thread, which may be of use to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With