Coding⏱️ 2 min read📅 2026-06-03

How to Fix: JavaScript: Check if mouse button down?

Detect if mouse button is down in JavaScript after mousedown event.

Quick Answer: Use the 'ontouchstart' and 'ontouchmove' events to track touch input, or use a library like 'mouse-tracking' to achieve similar results.

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?

💡 How to Detect Mouse Button State

You can use the document.getElementById('mouseButton').onclick property in combination with a variable that tracks the state of the mouse button.

In this example, we'll create a function called isMouseButtonDown that returns true if the mouse button is down and false otherwise.

var mouseButton = document.getElementById('mouseButton');var mouseButtonDown = false;function isMouseButtonDown(event) {  if (event.button === 0 && mouseButtonDown) {    return true;  } else if (event.button === 0) {    mouseButtonDown = true;  } else if (event.button !== 0) {    mouseButtonDown = false;  }  return mouseButtonDown;}document.addEventListener('mousedown', isMouseButtonDown);document.addEventListener('mouseup', () => mouseButtonDown = false);

✅ Example Usage

You can use this function like so:

console.log(isMouseButtonDown({ button: 0 })); // trueconsole.log(isMouseButtonDown({ button: 1 })); // false

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions