How to know when the mouse moves if the button is pressed

Hi, I have a function that I need to access only if the mouse moved when the mouse botton is pressed

You can do that by using a variable to track whether your mouse is currently pressed or not. If the mouse is currently pressed, your variable will indicate that. The following code snippet shows how that can be done:

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Mouse Example</title>
<style>
  #circle {
    width: 250px;
    height: 250px;
    margin: 20;
    background-color: #333;
    border-radius: 50%;
  }

  body {
    background-color: yellow;
  }

</style>
</head>

<body>

  <div id="circle"></div>

  <script>
  var myElement = document.querySelector("#circle");
  var mousePressed = false;

  myElement.addEventListener("mousedown", pressed, false);
  myElement.addEventListener("mouseup", released, false);
  myElement.addEventListener("mousemove", moved, false);

  function pressed(e) {
    mousePressed = true;
  }

  function released(e) {
    mousePressed = false;
  }

  function moved(e) {
    if (mousePressed) {
      console.log("Mouse moved while mouse is pressed down!");
    }
  }


  </script>
</body>
</html>

When you click on the div, the mousePressed variable goes from true to false. If you press and keep holding, the mousePressed variable stays at true. If you move your mouse at the same time, you know that the user was moving their mouse while the mouse button was pressed :stuck_out_tongue:

Cheers,
Kirupa

Thank you very much you are very fast to respond !!

1 Like