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

**URL:** <https://forum.kirupa.com/t/how-to-know-when-the-mouse-moves-if-the-button-is-pressed/636521>\
**Category:** Uncategorized\
**Created:** [April 27, 2017, 11:21pm UTC](https://forum.kirupa.com/t/how-to-know-when-the-mouse-moves-if-the-button-is-pressed/636521 "2017-04-27T23:21:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![luis\_vera](https://avatars.discourse-cdn.com/v4/letter/l/9fc29f/32.png) [@luis\_vera](https://forum.kirupa.com/u/luis_vera)\
**Post date:** [April 27, 2017, 11:21pm UTC](https://forum.kirupa.com/t/how-to-know-when-the-mouse-moves-if-the-button-is-pressed/636521/1 "2017-04-27T23:21:10Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [April 28, 2017, 12:29am UTC](https://forum.kirupa.com/t/how-to-know-when-the-mouse-moves-if-the-button-is-pressed/636521/2 "2017-04-28T00:29:22Z")

</div>

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 😛

Cheers,  
Kirupa

---

<div class="post-metadata">

**Author:** ![luis\_vera](https://avatars.discourse-cdn.com/v4/letter/l/9fc29f/32.png) [@luis\_vera](https://forum.kirupa.com/u/luis_vera)\
**Post date:** [April 28, 2017, 1:09am UTC](https://forum.kirupa.com/t/how-to-know-when-the-mouse-moves-if-the-button-is-pressed/636521/3 "2017-04-28T01:09:32Z")

</div>

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