I have developed a simple script for draggable elements, however, I am facing an issue. Whenever I move the mouse quickly, the element loses focus.
Is there a way to improve the stability of the dragging functionality regardless of how fast I move the mouse?
You can view the demo I created here: https://www.w3schools.com/code/tryit.asp?filename=GGPV1ESRELL8
<html>
<head>
<style>
.tester {
position: absolute;
width: 150px;
height: 150px;
box-shadow: 0 0 10px black;
background-color: white;
cursor: pointer;
}
</style>
</head>
<body>
<div class='tester'></div>
<script>
let tester = document.querySelector('.tester');
let draggable = false;
let offX;
let offY;
tester.onmousedown = (e) => {
e = e || window.event;
offX = e.offsetX;
offY = e.offsetY;
draggable = true;
tester.style.backgroundColor = 'indigo';
}
tester.onmouseup = () => {
draggable = false;
tester.style.backgroundColor = 'white';
}
document.body.onmousemove = (e) => {
e = e || window.event;
if (draggable){
tester.style.left = (e.pageX - offX) + 'px';
tester.style.top = (e.pageY - offY) + 'px';
}
}
</script>
</body>
</html>