user81993 user81993 - 3 months ago 24
Javascript Question

Checking if mouse buttons are down without listening to an event?

I'm building a dragging widget thingy, it listens to 'mouseup'/'mousedown' events from the interactive element.

Works fine most of the time but I've found the 'mouseup' to be a bit unreliable. Is there an event independent way of checking whether the mouse buttons are up/down? I could attach it to a timer or the mousemove event to make it foolproof.


You have to use an event however you can have script from within the events to assign the state of the mouse down that you can test later.

var isMouseDown = false;
document.addEventListener("mousedown", function()
  isMouseDown = true;
document.addEventListener("mouseup", function()
  isMouseDown = false;
if (isMouseDown == true) { ... }