Best way to run mousemove only on mousedown with pure javascript?

Alyona picture Alyona · Dec 27, 2015 · Viewed 18.2k times · Source

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 run mousemove only while mousedown == 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 the pressedMouse variable. Can onmousemove event be prevented from firing if mousedown not in use?

Answer

CoderPi picture CoderPi · Dec 27, 2015

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
});