How to make DOM object mouse movement fluid?
Problem Description:
I’m trying to create a function which can move a page element without having to reference it specifically.
function testmove(obj, event) {
document.getElementById(obj.id).addEventListener("mousemove", move(obj,event));
}
function move(obj, event) {
document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;
document.getElementById(obj.id).style.position = 'absolute';
document.getElementById(obj.id).style.left = event.clientX + "px";
document.getElementById(obj.id).style.top = event.clientY + "px";
}
This is the original code which worked fluidly:
function testmove(e) {
document.addEventListener('mousemove', logmovement);
}
function logmovement(e) {
document.getElementById("test").innerText = e.clientX + ' ' + e.clientY;
document.getElementById("test").style.position = 'absolute';
document.getElementById("test").style.left = e.clientX + "px";
document.getElementById("test").style.top = e.clientY + "px";
mousemove = true;
}
Any help is greatly appreciated!
Solution – 1
You’re attaching the listener to the element rather than the document so it will only respond when the mouse is positioned on that element.
You need to assign a function to the listener. At the moment you’re assigning the result of calling the
move
function to the listener.
// Pass in the object
function testmove(obj) {
// Add the listener to the document element as in the
// working example. Pass a function that calls `move` to the
// listener.
document.addEventListener("mousemove", () => move(obj, event));
}
function move(obj, event) {
document.getElementById(obj.id).innerText = event.clientX + ' ' + event.clientY;
document.getElementById(obj.id).style.position = 'absolute';
document.getElementById(obj.id).style.left = event.clientX + "px";
document.getElementById(obj.id).style.top = event.clientY + "px";
}
const obj = { id: 'move' };
testmove(obj);
<div id="move">Move</div>