Issue
I'm building a firefox extension that outputs a movable div that is controlled by the keyboard but when I try moving down or left (your left when looking at your screen) it doesn't move until I try moving in the opposite direction and then it jumps to where it supposed to have been after it was moved. Please help me find out the reason for this and a solution, thanks here's my code:
let pointer: HTMLDivElement = document.createElement("div");
pointer.style.backgroundColor = "red";
pointer.style.width = "20px";
pointer.style.height = "20px";
pointer.style.borderRadius = "10px";
pointer.classList.add("pointer");
pointer.style.position = "absolute";
document.body.append(pointer);
let x: number = 0;
let y: number = 0;
document.onkeydown = (e) => {
if (e.key === "l")
pointer.style.left = (x += 5) + "px";
else if (e.key === "h")
pointer.style.right = (x -= 5) + "px";
else if (e.key === "k")
pointer.style.top = (x -= 5) + "px";
else if (e.key === "j")
pointer.style.bottom = (x += 5) + "px";
}
Solution
This example will work
let pointer: HTMLDivElement = document.createElement("div");
pointer.style.backgroundColor = "red";
pointer.style.width = "20px";
pointer.style.height = "20px";
pointer.style.borderRadius = "10px";
pointer.classList.add("pointer");
pointer.style.position = "absolute";
document.body.append(pointer);
let left: number = pointer.offsetLeft;
let top1: number = pointer.offsetTop;
document.onkeydown = (e) => {
if (e.key === "l")
pointer.style.left = (left += 5) + "px";
else if (e.key === "h")
pointer.style.left = (left -= 5) + "px";
else if (e.key === "k")
pointer.style.top = (top1 += 5) + "px";
else if (e.key === "j")
pointer.style.top = (top1 -= 5) + "px";
}
Firstly, note that 0 as the top and left values do not represent the actual coordinates of the div. Instead, use the coordinates that become available after appending the div to the DOM, such as offsetLeft, x, y, etc.
To move your element, simply modify the left and top properties. You can find more information on coordinates in this resource.
Answered By - Vladislav Utkin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.