Based on javascript use drag to move element The objective is to adjust cursor position inside the square whenever dragged from/to anywhere. The below is a modified version in which I tried to eliminate having to save x
and y
offsets as variables for further reuse. Instead, I'm intending to replace the suggested method with $('.target').offset()
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>
As shown in the snippet, the console is showing a comparison between suggested solution x, x, suggested solution y, and y respectively. The offsets are identical or close depending on how fast the square is 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
64 72 19 27
...
which implies it should work if used for assignment. However, when these 2 lines:
target.style.left = e.clientX + x + 'px';
target.style.top = e.clientY + y + 'px';
are replaced with the commented out ones:
// target.style.left = offsetLeft + 'px';
// target.style.top = offsetTop + 'px';
The offsets calculated using $('.target').offsets()
keep infinitely increasing:
212 2408 424 2408
172 2416 423 2416
146 2424 418 2424
133 2432 409 2432
127 2440 401 2440
...
Is there something I'm missing here? Why the issue only happens when the offset values are used?