How do I listen for mouse button hold

351 Views Asked by At

I'm using Cocos2d-JS and need to find a way to listen for a mouse button hold. It seems limited in that there's only onMousemove, onMouseDown, and onMouseUp. All of those only get fired once. How do I use them to detect when a mouse button is being held down? I can't just use onMouseDown since that's being used to perform an action if the button is clicked.

1

There are 1 best solutions below

0
Daniel Deulin On

I can suggest the following solution for this. You can have a counter. onMouseDown will launch a method that will increment the counter via setInterval and check whether the counter reached the target value. If the value is reached, it will trigger whatever you want to be triggered by mouse button hold. onMouseUp will wipe off the interval counter. Here is the simplified code. Assuming these to be methods of an object.

onMouseDown: function() {
    this.launchTimer();
},

launchTimer: function() {
   //Timer will update every 100ms
   this.counter = 0;
   this.timer = setInterval(() => {

       //Assume our target value is 1s or 1000ms
       if (this.counter === 1000) {
           //Launch your function here
           this.onMouseHold();
           this.clearTimer();
         } else {
           this.counter += 100;
         }
       }, 100);

    this.timer();
},

clearTimer: function() {
   this.counter = 0;
   clearInterval(this.timer);
},

onMouseUp: function() {
   this.clearTimer();
}