Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda