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!
CodePudding user response:
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>
CodePudding user response:
function testmove(obj, event) {
document.getElementById(obj.id).addEventListener("mousemove", move);
}
function move(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";
}
function testmove(obj, event) {
document.getElementById(obj.id).addEventListener("mousemove", function() {
testmove(obj, event);
});
}
This will allow the move function to access the event object and use its clientX and clientY properties to update the position of the DOM object in a more fluid manner.