Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draggable effect doesn't work in Javascript

I have the follow code to make the div to become draggable:

let div = document.querySelector('div')
div.onmousedown = function() {
  div.addEventListener('mousemove', move, true)
}
window.onmouseup = function() {
  window.removeEventListener('mousemove', move, true)
}

function move(e) {
  this.style.position = 'absolute'
  this.style.top = e.clientY + 'px'
  this.style.left = e.clientX + 'px'
}
div {
  background: red;
  width: 100px;
  height: 100px;
}
<div></div>

I am not sure why, this code doesn't work properly as I expected.

Sometimes, when I just hover the div, it position will also change and that is what I don't expect. I checked the code for several times, but I didn't define the mouseover effect.

Could anyone tell me what I did wrong and how to fix it?

Thanks for any responds!

like image 424
James Avatar asked Nov 16 '25 19:11

James


1 Answers

You have to remove the event listener from the div, not the window:

I also centered the div when the user is dragging it, so the mouse has no chance to leave the div.

let div = document.querySelector('div');
function move(e) {
  this.style.position = 'absolute'
  this.style.top = e.clientY - (this.offsetHeight  / 2) + 'px'
  this.style.left = e.clientX - (this.offsetWidth / 2) + 'px'
}

div.addEventListener('mousedown', function() {
  this.addEventListener('mousemove', move, true);
});

window.addEventListener('mouseup', function() {
  div.removeEventListener('mousemove', move, true);
});
div {
  background: red;
  width: 100px;
  height: 100px;
}
<div></div>
like image 128
YourBrainEatsYou Avatar answered Nov 19 '25 10:11

YourBrainEatsYou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!