I tried to detect which mouse button -if any- is the user pressing during a mousemove event under jQuery, but I’m getting ambiguous results:
no button pressed: e.which = 1 e.button = 0
left button pressed: e.which = 1 e.button = 0
middle button pressed: e.which = 2 e.button = 1
right button pressed: e.which = 3 e.button = 2
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>$('#whichkey').bind('mousemove',function(e){
$('#log').html(e.which + ' : ' + e.button );
}); </script>
</body>
</html>
How can I tell the difference between left mouse button pressed and no button at all?
You can write a bit of code to keep track of the state of the left mouse button, and with a little function you can pre-process the event variable in the
mousemoveevent.To keep track of the state of the LMB, bind an event to document level for
mousedownandmouseupand check fore.whichto set or clear the flag.The pre-processing is done by the
tweakMouseMoveEvent()function in my code. To support IE versions < 9, you have to check if mouse buttons were released outside the window and clear the flag if so. Then you can change the passed event variable. Ife.whichwas originally 1 (no button or LMB) and the current state of the left button is not pressed, just sete.whichto0, and use that in the rest of yourmousemoveevent to check for no buttons pressed.The
mousemovehandler in my example just calls the tweak function passing the current event variable through, then outputs the value ofe.which.Try a live demo here: http://jsfiddle.net/G5Xr2/