Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 552
Alyona Avatar asked Dec 27 '15 19:12

Alyona


1 Answers

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
});
like image 160
CoderPi Avatar answered Nov 15 '22 17:11

CoderPi