After researching how to utilize JavaScript drag functionality to move elements, the goal is to dynamically adjust the cursor position within a square when dragged. In an attempt to simplify the process and avoid storing x and y offsets as separate variables for future use, I have modified the code snippet by utilizing $('.target').offset()
to obtain the top and left offset values.
(function () {
let x = 0;
let y = 0;
let target = document.querySelector('.target');
let mouseDown = false;
target.addEventListener(
'mousedown',
function (e) {
mouseDown = true;
target.style.position = 'relative';
x = target.offsetLeft - e.clientX;
y = target.offsetTop - e.clientY;
}
);
document.addEventListener(
'mouseup',
function () {
mouseDown = false;
}
);
document.addEventListener(
'mousemove',
function (e) {
event.preventDefault();
const offset = $(target).offset();
const offsetLeft = offset.left;
const offsetTop = offset.top;
if (mouseDown) {
console.log(
e.clientX + x,
offsetLeft,
e.clientY + y,
offsetTop
);
target.style.left = e.clientX + x + 'px';
target.style.top = e.clientY + y + 'px';
// target.style.left = offsetLeft + 'px'; // comment out for issue
// target.style.top = offsetTop + 'px';
}
}
);
})();
.target {
width: 100px;
height: 100px;
background-color: #0000FF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<div class="target"></div>
The above code shows that the console displays a comparison between the suggested solution coordinates and their respective offsets as the square is being dragged:
61 69 19 27
62 69 19 27
62 70 19 27
63 70 19 27
63 71 19 27
64 71 19 27
...
These values should work correctly when assigned. However, substituting the lines below:
target.style.left = e.clientX + x + 'px';
target.style.top = e.clientY + y + 'px';
with the commented-out lines causes issues with the offsets calculated using $('.target').offsets()
:
// target.style.left = offsetLeft + 'px';
// target.style.top = offsetTop + 'px';
The problem arises as the offset calculations with $('.target').offsets()
continue to increase exponentially:
212 2408 424 2408
172 2416 423 2416
146 2424 418 2424
133 2432 409 2432
127 2440 401 2440
...
There seems to be an oversight causing this issue. Why does it only occur when using the offset values?