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

144
Visualizações
MouseEvent.movementX and Y is different among Firefox, Chrome, and Edge

I'm trying to implement a simple dragging for my frontend project. Below is the minimal working example. In essence, I set position: relative to be able to control element position via style.left and style.top, and use MouseEvent.movementX and MouseEvent.movementY to update position according to the cursor movements.

<!DOCTYPE html>    
<head>
  <title>Drag-n-drop</title>
  <style>
    .dragme {
      position: relative;   
      width: 100px;
      height: 100px;
      background-color: grey;
    }
  </style>
</head>    
<body>

  <div class="dragme"></div>

  <script>
    const box = document.querySelector(".dragme");
    box.addEventListener("mousedown", dragStart);
    window.addEventListener("mouseup", dragStop);

    function dragStart(event) {
      window.addEventListener("mousemove", dragging);
    }

    function dragging(event) {
      const style = window.getComputedStyle(box);
      box.style.left = `calc(${style.left} + ${event.movementX}px)`;
      box.style.top = `calc(${style.top} + ${event.movementY}px)`;
    }

    function dragStop(event) {
      window.removeEventListener("mousemove", dragging);
    }
  </script>

</body>    
</html>

The problem is, this approach works as intended in Firefox, but in Chrome and Edge, the dragged element moves faster than the cursor. After some investigation, I realized that the source of the problem is highDPI screen. Replacing event.movementX by event.movementX / window.devicePixelRatio etc. makes Chrome and Edge perform dragging flawlessly, but not Firefox.

The only cross-browser solution I came up with is to use MouseEvent.screenX and MouseEvent.screenY instead and I'm perfectly fine with it. However, I'm still curious is there any ways to be able to use MouseEvent.movementX and MouseEvent.movementY across different browsers?

about 4 years ago · Juan Pablo Isaza
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