Is there a way to detect if a mouse button is currently down in JavaScript?
I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.
Is this possible?
Using jQuery, the following solution handles even the "drag off the page then release case".
I don't know how it handles multiple mouse buttons. If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.
I think the best approach to this is to keep your own record of the mouse button state, as follows:
and then, later in your code:
This is an old question, and the answers here seem to mostly advocate for using
mousedown
andmouseup
to keep track of whether a button is pressed. But as others have pointed out,mouseup
will only fire when performed within the browser, which can lead to losing track of the button state.However, MouseEvent (now) indicates which buttons are currently pushed:
MouseEvent.buttons
MouseEvent.which
(buttons
will be undefined for Safari) Note:which
uses different numbers frombuttons
for Right and Middle clicks.When registered on
document
,mousemove
will fire immediately as soon as the cursor reenters the browser, so if the user releases outside then the state will be updated as soon as they mouse back inside.A simple implementation might look like:
If more complicated scenarios are required (different buttons/multiple buttons/control keys), check out the MouseEvent docs. When/if Safari lifts its game, this should get easier.
If you're working within a complex page with existing mouse event handlers, I'd recommend handling the event on capture (instead of bubble). To do this, just set the 3rd parameter of
addEventListener
totrue
.Additionally, you may want to check for
event.which
to ensure you're handling actual user interaction and not mouse events, e.g.elem.dispatchEvent(new Event('mousedown'))
.Add the handler to document (or window) instead of document.body is important b/c it ensures that mouseup events outside of the window are still recorded.
Below jQuery example, when mouse is over $('.element'), color is changing depending on which mouse button is pressed.
As said @Jack, when
mouseup
happens outside of browser window, we are not aware of it...This code (almost) worked for me:
Unfortunately, I won't get the
mouseup
event in one of those cases: