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

171
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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