When creating a draggable map, it might act weird when you move your mouse too quickly or outside the window, for example:
However, if we listen to mouseup
and mousemove
on window
or document
, it works:
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const box = ...;
let lastClickPos = undefined;
const pos = [0, 0];
box.addEventListener('mousedown', (e) => {
if (event.which !== 1) return;
lastClickPos = [e.clientX, e.clientY];
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (lastClickPos) {
pos[0] += e.clientX - lastClickPos[0];
pos[1] += e.clientY - lastClickPos[1]
box.style.setProperty('left', pos[0] + 'px');
box.style.setProperty('top', pos[1] + 'px');
lastClickPos = [e.clientX, e.clientY];
}
});
document.addEventListener('mouseup', (e) => {
lastClickPos = undefined;
});