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

236
Visualizações
How to make drag event move in only one direction in javascript?

I'm using drag event for moving an element, but I didn't find a way to make it only move horizontally, it's there any clue for this? Thanks in advance!

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

0

There is three steps we need to do first we get the current mouse x position second we calculate the distance it has move and the direction by newX = oldX - e.clientX saying subtract old x with current mouse x this way we get something like -3 or 2 or -1 you see we have the distance the direction - or + Third step we update the element horizontal position by element.style.left = (element.offsetLeft - newX) + "px"

There are more details in the comments in the code. let me know if its not clear

var oldX = 0, newX = 0; // for storing X (horizontal) positions
var element = document.getElementById("mydiv"); // The element you want to drag

// We do the dragging here
function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  newX = oldX - e.clientX; // to calculate how much we have moved
  oldX = e.clientX; // store current value to use for next move
  element.style.left = (element.offsetLeft - newX) + "px"; // update left position
}

// we do this so there is not multiple event handlers
function closeDragElement() {
  document.onmouseup = null;
  document.onmousemove = null;
}

// when mouse down on element attach mouse move and mouse up for document
// so that if mouse goes outside element still drags
function dragMouseDown(e) {
  e = e || window.event;
  e.preventDefault();
  oldX = e.clientX; // store current value to use for mouse move calculation
  document.onmouseup = closeDragElement;
  document.onmousemove = elementDrag;
}

element.onmousedown = dragMouseDown;
#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #2196F3;
  text-align: center;
  border: 1px solid #d3d3d3;  
  padding: 10px;  
  cursor: move;  
  color: #fff;
}
<div id="mydiv">
  Click here to move
</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