How to check the current state of a mouse button Using Javascript

I want the mouse state to be down or up

document.onmousemove = mouseMove; document.onmousedown = mouseDown; document.onmouseup = mouseUp; function mouseMove(ev) { mouseState=""; //How can I know the state button of mouse button from here if(mouseState=='down') { console.log('mouse down state') } if(mouseState=='up') { console.log('mouse up state') } } function mouseDown(ev) { console.log('Down State you can now start dragging'); //do not write any code here in this function } function mouseUp(ev) { console.log('up state you cannot drag now because you are not holding your mouse') //do not write any code here in this function } 

When I move my mouse, the program should now show the desired value of mouseState up or down on the console

+4
source share
2 answers

You can check the MouseEvent.which property.

 function mouseMove(ev) { if(ev.which==1) { console.log('mouse down state with left click'); } else if(ev.which==3) { console.log('mouse down state with right click'); } else { console.log('mouse update'); } } 
+3
source

You just need to create a variable for it.

 document.onmousemove = mouseMove; document.onmousedown = mouseDown; document.onmouseup = mouseUp; var mouseState = "up"; function mouseMove(ev) { //How can I know the state of mouse from here if(mouseState=='down') { console.log('mouse down state') } if (mouseState=='up') { console.log('mouse up state') } } function mouseDown(ev) { mouseState = "down"; console.log('Down State you can now start dragging'); //do not write any code here in this function } function mouseUp(ev) { mouseState = "up"; console.log('up state you cannot drag now because you are not holding your mouse') //do not write any code here in this function } 

You should watch the event on "mousemove" by running it in the console. There may be a property that indicates that the mouse state, like the keypress event, has a property that tells you whether the shift button is pressed. But this may not be compatible with the browser.

+2
source

All Articles