'setPointerCapture behaves differently in Chrome and Firefox
I have a bunch of square div inside flexboxes. When I press a mouse button inside a square, I would like the background of the target square to change. I would like to capture the mouse, so when I move the mouse outside the captured square and release the mouse button the background should change back to its original color.
This is a little difficult to describe, so here's the code. https://codepen.io/tqphan/pen/qBWaVod
window.addEventListener('mousedown', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
target.classList.add("pressed")
target.setPointerCapture(e.pointerId);
}, true);
window.addEventListener('mouseup', function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
target.classList.remove("pressed")
target.releasePointerCapture(e.pointerId);
}, true);
To reproduce the problem, please follow these steps:
- Press the left mouse button over a square.
- While the left mouse button is held down, drag the mouse outside the square.
- Release the left mouse button.
In Firefox, it works as I expected. In Chrome, the background doesn't change back to its original color.
I tried capturing the events for window and document.
edit: It appears pointer capture and release are not executed in Chrome.
pen.js:6 Uncaught DOMException: Failed to execute 'setPointerCapture' on 'Element': No active pointer with the given id is found.
pen.js:12 Uncaught DOMException: Failed to execute 'releasePointerCapture' on 'Element': No active pointer with the given id is found.
Solution 1:[1]
I had the same or similar problem, setPointerCapture() worked perfectly for my app on FireFox, but not on Chrome. On Chrome it seemed to do nothing, no error-messages either.
I finally figured out why. On Chrome setPointerCapture() seems to only capture "pointer events" meaning events named like 'pointermove' and 'pointerup, NOT events 'mousemove' and 'mouseup' etc. This happens on Chrome version 97.0.4692.99 (Official Build) (64-bit)
On FireFox setPointerCapture() captures also "mouse -events" like 'mousemove' and 'mouseup'. Those were the ones for which I had set event-handlers in my DOM-element. Therefore they worked fine on FireFox.
The solution was to modify my code so that instead of adding handlers for 'mousemove' and 'mouseup' I now add handlers for 'pointermove' and 'pointerup'. After this change it works equally well on both FireFox and Chrome.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Panu Logic |
