Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

There were two issues,

  1. You were removing the event lister from the window, not on the div.
  2. You need to consider the offset values to correctly position the div when moving.

let div = document.querySelector('div')
let offsetX = "";
let offsetY = "";

div.onmousedown = function(e) {
  var domRect = this.getBoundingClientRect();
  offsetX = e.clientX - domRect.left;
  offsetY = e.clientY - domRect.top;
  div.addEventListener('mousemove', move, true)
}

window.onmouseup = function() {
  div.removeEventListener('mousemove', move, true)
}

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

about 4 years ago · Juan Pablo Isaza Relatório

0

dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#mydivheader {
  height: 100px;
  width: 100px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
<h1>Draggable DIV Element</h1>

<div id="mydiv">
  <div id="mydivheader"></div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda