Best way to run mousemove only on mousedown with pure javascript?
Solution 1
You can prevent the onMouseMove-Function to be called, by removing it from the listener:
myObject.addEventListener("mousedown", function(e){
mouseDownFunction(e);
myObject.onmousemove = function(e) {
mouseMoveFunction(e);
}
});
myObject.addEventListener("mouseup", function(e){
myObject.onmousemove = null
});
Solution 2
Since you're going to be adding an event handler and then removing it, potentially over and over, define the mouseMove function first ready to accept an event object:
function mouseMoveFunction(e) {
//stuff
}
Now you can merely add a reference to that function rather than creating a new anonymous function that calls it whenever mousedown activates. Plus, since we have that reference, we might as well use the standard add/remove-EventListener methods.
myObject.addEventListener("mousedown", function(e){
mouseDownFunction(e);
this.addEventListener("mousemove", mouseMoveFunction);
});
myObject.addEventListener("mouseup", function(e){
this.removeEventListener("mousemove", mouseMoveFunction);
});
Alyona
Updated on July 19, 2022Comments
-
Alyona almost 2 years
I do not want any unnecessary loops occurring for
mousemove
event. So I became interested, in terms of performance/best practice what would be the best way to runmousemove
only whilemousedown == true
? Currently I'm using:var pressedMouse = false; myObject.addEventListener("mousedown", function(e){ mouseDownFunction(e); pressedMouse = true; myObject.onmousemove = function(e) { if(pressedMouse == true){ mouseMoveFunction(e); } } }); myObject.addEventListener("mouseup", function(e){ pressedMouse = false; });
mouseMoveFunction()
isn't being called because of thepressedMouse
variable. Canonmousemove
event be prevented from firing ifmousedown
not in use? -
Alyona over 8 yearsBut can I prevent
mousemove
from even firing withoutmousedown
event? -
wordbug almost 6 yearsBut what if there was an unknown number of mousemove events associated to myObject, and you wanted to remove only the one you had set?
-
CoderPi almost 6 years@wordbug do you mean by using
addEventListener
? -
wordbug almost 6 yearsYes. It'd be consistent with your other uses (mousedown and mouseup), and it wouldn't interfere with other code that might coexist with this snippet.
-
Frikster over 5 yearsThis fails for me because of reasons outlined here: stackoverflow.com/a/10444156/2734863