How to stop onmouseup function inside mouse move event listener

1k Views Asked by At

I have the following code. As can be seen, I have an event listener that triggers when the mouse button is pressed down on a div ("myDiv"). If the mouse is moved the div moves, and then when the mouse button is released, a messaged is logged to the console. Problem is, every time after that, even when the mouse isn't over the div, if the mouse button is released, the same message is logged to the console. I've managed to turn off the onmousemove function with "document.onmousemove = null". But how do I stop the mouseup function from perpetually executing? Vanilla javascript only. Thanks

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

myDiv.addEventListener("mousedown", function(event) {

  document.onmousemove = function(event) {
    myDiv.style.left = event.clientX + "px";
  };

  document.onmouseup = function(event) {
    document.onmousemove = null;
    
    console.log("you moved the div");

  };

});
#div {
width: 100px;
height: 100px;
position: absolute;
background-color: rgba(0,50,150,1);
}
<div id="div"></div>

2

There are 2 best solutions below

0
Emre Koc On

Move your functions out of the first listener and add/remove the listeners when needed:

myDiv.addEventListener("mousedown", function(event) {
    // Add the listeners
    document.addEventListener('mousemove', mouseMove);
    document.addEventListener('mouseup', mouseUp);
});

function mouseMove(event) {
    myDiv.style.left = event.clientX + "px";
};

function mouseUp (event) {
    console.log("you moved the div");
    // Remove the listeners
    document.removeEventListener('mousemove', mouseMove);
    document.removeEventListener('mouseup', mouseUp);
};
0
Huy Ngo On

The simplest way to do it is to remove the event listener after it is moved:

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

myDiv.addEventListener("mousedown", function(event) {

  document.onmousemove = function(event) {
    myDiv.style.left = event.clientX + "px";
  };

  document.onmouseup = function(event) {
    document.onmousemove = null;
    
    console.log("you moved the div");
    document.onmouseup = null;
  };

});
#div {
width: 100px;
height: 100px;
position: absolute;
background-color: rgba(0,50,150,1);
}
<div id="div"></div>