user81993 user81993 - 1 year ago 60
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.

Answer Source

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) { ... }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download