0

This is an oft-asked question, but with a twist.

I need to figure out if the mouse is held down. Okay. I do some research. I find this lovely question/answer: JavaScript: Check if mouse button down? that gives multiple examples of how to keep track of whether the mouse is held down. For my uses, I've strained that out to this snippet:

$(document).mousedown(function(){
    Game.isMouseDown = true;
});
$(document).mouseup(function(){
    Game.isMouseDown = false;
    Game.lastSquare = [];
});

It works fairly well, except for a few instances. I'm in the process of heavy debugging at the moment, so I almost always have the debugger open. When I mouseover the debugger and release (such as when I'm using breakpoints, or just moving my mouse around quickly), hovering over the Game div without any mouse button held produces the same result as holding the mouse button down.

I need to prevent this from happening, and I believe the way to do that is to request of the DOM if the mouse is held down instead of asking my Game.isMouseDown variable set by events. But through all my research, I can't find how to ask the DOM that question.

RoboticRenaissance
  • 1,130
  • 1
  • 10
  • 17

1 Answers1

0

Check for the mousemove event which itself captures how many buttons are pressed.

$(document).mousemove(function(e){
    if(e.buttons > 0){
        Game.isMouseDown = true;
    } else {
        Game.isMouseDown = false;
    }
});

https://developer.mozilla.org/en-US/docs/Web/Events/mousemove

jered
  • 11,220
  • 2
  • 23
  • 34
  • Thank you. This worked beautifully. I integrated this directly into the Game div mouse events which were already in place, and no longer need the Game.isMouseDown variable. I also got rid of the if statement inside the function that is triggered by certain mouse events. I also feel like a n00b. – RoboticRenaissance Dec 11 '15 at 21:43