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

168
Vistas
Detect mouse drag and direction using pure javascript

I am trying to detect the mouse direction when dragging the mouse. When the mouse button is down and the user drags the mouse, I want the text to change to left or right depending on the mouse drag direction.

Here's my code.

var divOverlay = document.getElementById ("div");

var dragged = false
window.addEventListener('mousedown', function () { dragged = false })
document.addEventListener('mousemove', function () { dragged = true })
window.addEventListener('mouseup', function(e) {

    
        if (dragged == true && e.pageX <= 0) {
            direction = "left"
        } else if (dragged == true && e.pageX >= 0) {
            direction = "right"
        }
        
        divOverlay.innerHTML = direction;
        
        oldx = e.pageX;
})
#div {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="div"></div>

I don't think I'm too far off but I can't workout what I am doing wrong so I need some help.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Here you go. It just needed a minor tweak.

var divOverlay = document.getElementById ("div");

var dragged = false
var oldX = 0;
window.addEventListener('mousedown', function (e) { oldX = e.pageX; dragged = false })
document.addEventListener('mousemove', function () { dragged = true })
window.addEventListener('mouseup', function(e) {

    
        if (dragged == true && e.pageX < oldX) {
            direction = "left"
        } else if (dragged == true && e.pageX > oldX) {
            direction = "right"
        }
        
        divOverlay.innerHTML = direction;
        
        
})
#div {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="div"></div>

about 4 years ago · Santiago Trujillo Denunciar

0

You should add oldX to the position checking. You also need to initialize it.

var divOverlay = document.getElementById("div");

var dragged = false
var oldX = 0;

window.addEventListener('mousedown', function (e) {
  dragged = false;

  // set start position of drag
  oldX = e.pageX;
});

document.addEventListener('mousemove', function () {
  dragged = true
});

window.addEventListener('mouseup', function (e) {
  // compare drag end position with start position
  if (dragged == true && e.pageX <= oldX) {
    direction = "left"
  } else if (dragged == true && e.pageX > oldX) {
    direction = "right"
  }

  divOverlay.innerHTML = direction;
});
#div {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="div"></div>

about 4 years ago · Santiago Trujillo Denunciar

0

Having a separate function to handle the relative direction of the mouse on the X axis is more likely something suitable for what you would like to do. Instead of trying to update variables, remove the eventListener once the mouse is released.

See below as an example:

    const body = document.body;
  const container = document.getElementById('container');
  const directionTag = document.getElementById("direction");

  const moveFunc = function (e) {
    let direction;
    if (e.movementX < 0) {
      container.style.backgroundColor = "red";
      direction = "left";
    } else if (e.movementX > 0) {
      container.style.backgroundColor = "blue";
      direction = "right";
    }
    if (typeof direction !== "undefined") {
      directionTag.innerHTML = direction;
    }
  };

  body.onmousedown = function () {
    body.addEventListener("mousemove", moveFunc);
  };

  body.onmouseup = function () {
    body.removeEventListener("mousemove", moveFunc);
  };
#container {
    height: 150px;
    margin: 20px;
    padding: 20px;
    width: 300px;
    border: 1px solid #888;
}
<body>
    <div id="container">This will change when you hold down</div>
  <p id="direction">Unset</p>
</body>

about 4 years ago · Santiago Trujillo 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