Search code examples
javascriptonclicksubstitutiononmousedownonmousemove

onMouseMove + onMouseDown to call function


I have a real problem over here. I want a function to get called only when an object is clicked and when when the mouse is moved over the object. Here is an example (ignore the weird syntax) to get your understanding:

<div onMouseMove+onMouseDown="function()" ... ></div>

I was thinking of a way to solve this. What if I make a onMouseDown that trigger a function that will change the name of my onMouseMove - function, and use a "filler" or a "substitute" function? Let me explain:

<div id="object" onMouseMove="substituteFiller()" onMouseDown="nameChanger()" ... ></div>
<script>
    function nameChanger(){
        document.getElementById("object").onMouseMove = "theRealFunction()"; 
    }
</script>
<script>
    function theRealFunction() ... 

When I move the mouse over the object nothing will happen, because the function substituteFiller() won't work. But, when the mouse has clicked on the object the onMouseMove- function will be the correct one, theRealFunction(), and theRealFunction() will now get called when the mouse moves.

This way I could activate/call theRealFunction() only when the object is clicked and when the mouse moved. However, it does not work.

To be clear: how can I change the name of the function that is being called? How can I make a function to be called only when an object is clicked and mouse moved?

Best regards, hope you understood! If not, comment I guess!


Solution

  • Okay, all you need to do is separately register 3 event handlers:

    1. mouse down
    2. mouse up
    3. mouse move

    You will have a boolean flag toggled to true and false on mouse down and up respectively. Then, on the mouse move handler, you need to check if the flag is true, which would mean the mouse button is down. Finally, we check to see if the cursor has actually moved from its initial position.

    Here's the JSFiddle.

    var example = document.getElementById("example");
    var position = {
      X: 0,
      Y: 0
    };
    
    example.onmousedown = function (down) {
      downFlag = true;
      // Record click position
      position.X = down.clientX;
      position.Y = down.clientY;
    };
    
    example.onmouseup = function (up) {
      downFlag = false;
    };
    
    example.onmousemove = function (move) {
      if (downFlag) {
        if (position.X !== move.clientX || position.Y !== move.clientY) {
          // Do stuff here
        }
      }
    };