I'm facing an issue with dragging an element just a bit on a mousedown event to reveal a new item underneath. However, whenever I try to move it, the element jumps all the way to the right side of the window instead of where I intended it to go. I have experimented with changing positions from 'relative' to 'absolute', setting fixed x and y positions, and making them relative to the mouse event, but the problem persists.
It seems like there's something fundamental that I am missing here. In my background, I've heavily relied on vue.js
to handle DOM manipulation, as I don't have much experience in this area. This challenge arose in a Vue project initially, leading me to believe it was a Vue-related issue, which was later proven not to be the case.
document.getElementById("red").addEventListener("mousedown", mouseDown);
function mouseDown(e) {
const el = e.target;
// const x = e.pageX;
// const y = e.pageY;
const rect = el.getBoundingClientRect();
const x = rect.left + 20;
const y = rect.top + 20;
el.style.left = `${x}px`
el.style.top = `${y}px`
const newrect = el.getBoundingClientRect();
document.getElementById("from").innerHTML = "drag from: " + rect.left + ", " + rect.top;
document.getElementById("to").innerHTML = "try to drag to: " + x + ", " + y;
document.getElementById("result").innerHTML = "dragged to: " + + newrect.left + ", " + newrect.top;
}
.box {
position:relative;
margin: auto;
border: 3px solid #73AD21;
width: 200px;
height: 250px;
}
.button {
position:relative;
background-color: red;
color: white;
padding: 10px 20px;
text-align: center;
width: 100px;
font-size: 16px;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag Drop Test</title>
</head>
<body>
<div id="app" align="center" class="box">
<button id="red" class="button" >Red</button>
<p id="from"></p>
<p id="to"></p>
<p id="result"></p>
</div>
</body>
</html>