1 year ago
#202472
Yuri
MouseEvent.movementX and Y is different among Firefox, Chrome, and Edge
I'm trying to implement a simple dragging for my frontend project. Below is the minimal working example. In essence, I set position: relative
to be able to control element position via style.left
and style.top
, and use MouseEvent.movementX
and MouseEvent.movementY
to update position according to the cursor movements.
<!DOCTYPE html>
<head>
<title>Drag-n-drop</title>
<style>
.dragme {
position: relative;
width: 100px;
height: 100px;
background-color: grey;
}
</style>
</head>
<body>
<div class="dragme"></div>
<script>
const box = document.querySelector(".dragme");
box.addEventListener("mousedown", dragStart);
window.addEventListener("mouseup", dragStop);
function dragStart(event) {
window.addEventListener("mousemove", dragging);
}
function dragging(event) {
const style = window.getComputedStyle(box);
box.style.left = `calc(${style.left} + ${event.movementX}px)`;
box.style.top = `calc(${style.top} + ${event.movementY}px)`;
}
function dragStop(event) {
window.removeEventListener("mousemove", dragging);
}
</script>
</body>
</html>
The problem is, this approach works as intended in Firefox, but in Chrome and Edge, the dragged element moves faster than the cursor. After some investigation, I realized that the source of the problem is highDPI screen. Replacing event.movementX
by event.movementX / window.devicePixelRatio
etc. makes Chrome and Edge perform dragging flawlessly, but not Firefox.
The only cross-browser solution I came up with is to use MouseEvent.screenX
and MouseEvent.screenY
instead and I'm perfectly fine with it. However, I'm still curious is there any ways to be able to use MouseEvent.movementX
and MouseEvent.movementY
across different browsers?
javascript
drag-and-drop
cross-browser
mouseevent
dpi
0 Answers
Your Answer