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

21,497

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);
});
Share:
21,497
Alyona
Author by

Alyona

Updated on July 19, 2022

Comments

  • Alyona
    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 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?

  • Alyona
    Alyona over 8 years
    But can I prevent mousemove from even firing without mousedown event?
  • wordbug
    wordbug almost 6 years
    But 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
    CoderPi almost 6 years
    @wordbug do you mean by using addEventListener ?
  • wordbug
    wordbug almost 6 years
    Yes. 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
    Frikster over 5 years
    This fails for me because of reasons outlined here: stackoverflow.com/a/10444156/2734863