Looks like you need a combination of disabling the contextmenu
(if you can, some browsers don't allow it) and mouseup
. Also, it's useful to make whatever the user is clicking not user-selectable (more here) so that repeated clicks don't select text.
This works for me on Chrome, see comments:
// Avoid the context menu popup
window.addEventListener("contextmenu", function(e) {
e.preventDefault();
}, false);
// Listen for mouseup
window.addEventListener("mouseup", function(e) {
switch (e.button) {
case 0: // Primary button ("left")
speedUp();
break;
case 2: // Secondary button ("right")
speedDown();
break;
}
}, false);
// Current speed
var speed = 0;
showSpeed();
// Speed functions
function speedUp() {
++speed;
showSpeed();
}
function speedDown() {
--speed;
showSpeed();
}
function showSpeed() {
document.getElementById("speed").innerHTML = speed;
}
/* From https://stackoverflow.com/questions/826782/how-to-disable-text-selection-highlighting-using-css */
body {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
not supported by any browser */
}
<div>Current speed: <span id="speed">0</span>
</div>
<div>Left-click to speed up</div>
<div>Right-click to slow down</div>
Here's a simpler example just demonstrating detecting when mouse buttons are pressed and released:
// Avoid the context menu popup
window.addEventListener("contextmenu", function(e) {
e.preventDefault();
}, false);
// Listen for mousedown
window.addEventListener("mousedown", function(e) {
handle(e, true);
}, false);
// Listen for mouseup
window.addEventListener("mouseup", function(e) {
handle(e, false);
}, false);
// Our main handler
function handle(e, down) {
var id;
switch (e.button) {
case 0: // Primary button ("left")
id = "primary-status";
break;
case 2: // Secondary button ("right")
id = "secondary-status";
break;
}
if (id) {
document.getElementById(id).innerHTML = down ? "Down" : "Up";
}
}
/* From https://stackoverflow.com/questions/826782/how-to-disable-text-selection-highlighting-using-css */
body {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
not supported by any browser */
}
<div>
Primary ("left") mouse button:
<span id="primary-status">Unknown</span>
</div>
<div>
Secondary ("right") mouse button:
<span id="secondary-status">Unknown</span>
</div>
Side note: Many users configure their mice so that holding both buttons down simulates the middle button (e.button == 1
). You may need to handle that...