Gamepad: buttons property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The buttons
property of the Gamepad
interface returns an array of gamepadButton
objects representing the buttons present on the device.
Each entry in the array is 0
if the button is not pressed, and non-zero (typically 1.0
) if the button is pressed.
Each gamepadButton
object has two properties:
pressed
-
A boolean indicating whether the button is currently pressed (
true
) or unpressed (false
). value
-
A floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 – 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed.
Value
An array of gamepadButton
objects.
Examples
Depending on the type of button, we need to access the GamepadButton.value
or GamepadButton.pressed
properties. This
example supports both:
function gameLoop() {
const gp = navigator.getGamepads()[0];
if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
b--;
} else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
a++;
} else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
b++;
} else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
a--;
}
ball.style.left = `${a * 2}px`; // ball is a UI widget
ball.style.top = `${b * 2}px`;
requestAnimationFrame(gameLoop);
}
Specifications
Specification |
---|
Gamepad # dom-gamepad-buttons |
Browser compatibility
BCD tables only load in the browser