Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for element.setCapture in Chrome?

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?

like image 747
Pierre Arnaud Avatar asked Jun 14 '16 11:06

Pierre Arnaud


2 Answers

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.

like image 117
Pierre Arnaud Avatar answered Nov 03 '22 19:11

Pierre Arnaud


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.

like image 1
Gideon Pyzer Avatar answered Nov 03 '22 21:11

Gideon Pyzer