RFF
RFF

Reputation: 271

I want to detect whether the right or left mouse button is down during a mousemove event

I am using HTML5 and want to know if the right mouse button or left mouse button is held down during a mouse move. The right mouse button has event.button = 2 for the right button. The left button has event.button = 0. During the mousemove, event.button = 0 always. I have supplied some sample code. What am I doing wrong?

<!DOCTYPE html>

<html lang="en">

<head>

<title>demo on detecting mouse buttons</title>
<meta charset="utf-8"/>

<style>
#mycanvas{ border-style:solid; width:400px; height:400px; border-width:2px;}
</style>


<script type="text/javascript">

function detectDown(event)
{
var string = "Mouse Down, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,0,300,20);
context.fillText(string,0,10);
}

function detectMove(event)
{
var string = "Mouse Move, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,30,300,20);
context.fillText(string,0,40);
}

function detectUp(event)
{
var string = "Mouse Up, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,60,300,20);
context.fillText(string,0,70);
}
</script>

</head>

<!-- -->

<body>

<canvas id="mycanvas"onmousedown="detectDown(event)" onmouseup="detectUp(event)" onmousemove="detectMove(event)" >
</canvas>

</body>

</html>

Upvotes: 2

Views: 2994

Answers (2)

PuiMan Cheui
PuiMan Cheui

Reputation: 104

Actually, you can:

document.body.addEventListener('mousemove', e => console.log(`mousedown: ${(e.buttons | e.button) === 1} when mousemove`));
html, body {
  height: 100%;
}

div {
  border: 2px dashed #a10000;
  height: 100%;
  text-align: center;
}
<div>mousemove here</div>

Notice: when you want to run the code below IE8, use attachEvent to bind mousemove.

Upvotes: 1

N Rohler
N Rohler

Reputation: 4615

The mouse move event is necessarily button-agnostic. It reports mouse movement, regardless of whether buttons are pressed or not. You need to create a flag on mousedown that tracks which button is down; reset it on mouseup.

Upvotes: 4

Related Questions