A modern TypeScript library for handling gamepad input in web applications.
import { GamepadManager } from './dist/index.js';
GamepadManager automatically starts one requestAnimationFrame polling loop when the module is created. This is the simplest option and is a good fit for menus, tools, and smaller applications.
If your game already owns one authoritative frame loop, stop the library loop and poll exactly once from that loop:
GamepadManager.stopPolling();
function gameLoop() {
GamepadManager.pollGamepadStateOnce();
// Update input, simulation, and rendering in your chosen order.
requestAnimationFrame(gameLoop);
}
gameLoop();
Choose one polling owner. Do not leave automatic polling enabled while also calling pollGamepadStateOnce() or pollGamepadState() yourself. Two polling loops read the same device twice, repeat callback work, and can make controller input arrive out of order relative to the game's simulation.
Automatic polling is easier to integrate. Host-controlled polling is better when the game needs deterministic update ordering or already has a frame loop, but the game then owns the responsibility to poll once per frame. stopPolling() pauses only the library's loop; it does not disconnect controllers or clear their cached state.
The library owns device normalization, dead zones, connection state, and low-level events. The game should own higher-level questions such as which device currently controls the player, whether input is allowed in the current menu/gameplay context, and how competing devices are arbitrated.
// Listen for controller connections
GamepadManager.on('connect', (controller) => {
console.log(`Controller connected: ${controller.getDisplayName()}`);
// Set up event listeners
controller.addEventListener('buttondown', (button, value) => {
console.log(`${button} pressed with value: ${value}`);
});
controller.addEventListener('analogchange', (analog, position) => {
console.log(`${analog} moved to`, position);
});
// Test vibration
controller.vibratePreset('light-tap');
});
// Start listening for controllers
GamepadManager.on('disconnect', (controller) => {
console.log('Controller disconnected');
});
// Get all connected controllers
const controllers = GamepadManager.getControllers(); // Controller[]
// Get the main controller (first connected by default)
const mainController = GamepadManager.getMainController(); // Controller | null
// Get a specific controller by index
const controller = GamepadManager.getController(0); // Controller | null
// Set a different controller as main
GamepadManager.setMainController(1); // boolean
// Get controllers with metadata
const metadata = GamepadManager.getControllersWithMetadata();
// Returns: Array<{controller: Controller, index: number, isMain: boolean, connectionOrder: number}>
The library uses an event system. Events are emitted while controller state is being processed, so callbacks should stay lightweight and should avoid unnecessary allocations or logging in high-frequency paths.
controller.addEventListener('buttondown', (buttonName, value) => {
// Fired once when button is initially pressed
console.log(`${buttonName} pressed: ${value}`);
});
controller.addEventListener('buttonpress', (buttonName, value, repeat) => {
// Fired when a held button's reported value changes.
// It is not called every polling frame when the value is unchanged.
console.log(`${buttonName} held: ${value} (repeat: ${repeat})`);
});
controller.addEventListener('buttonup', (buttonName, value) => {
// Fired once when button is released
console.log(`${buttonName} released: ${value}`);
});
controller.addEventListener('analogchange', (analogName, position) => {
// Preferred gameplay event: one callback for a changed stick.
// The position object is reused and updated by the library; copy it if you
// need to retain a snapshot after this callback returns.
console.log(`${analogName}:`, position);
});
controller.addEventListener('axischange', (axisName, value, angle, repeat) => {
// Legacy/axis-specific event: X and Y are reported separately.
console.log(`${axisName}: ${value} at angle ${angle}`);
});
controller.addEventListener('grab', (analogName) => {
// Fired when analog stick starts being used
console.log(`${analogName} analog grabbed`);
});
controller.addEventListener('drop', (analogName) => {
// Fired when analog stick is released
console.log(`${analogName} analog dropped`);
});
// Unified button event - an alternative to buttondown/buttonpress/buttonup
controller.addEventListener('button', (buttonName, value, action) => {
console.log(`${buttonName}: ${value} (${action})`);
// Handle different actions
if (action === 'pressed') {
console.log(`${buttonName} was just pressed`);
} else if (action === 'released') {
console.log(`${buttonName} was just released`);
} else if (action === 'held') {
console.log(`${buttonName} is being held`);
}
});
Use one event family for one piece of behavior. Do not register both the unified event and the corresponding specific events for the same action.
| Need | Preferred event | Why |
|---|---|---|
| Different press, hold, and release behavior | buttondown / buttonpress / buttonup |
Precise lifecycle control |
| One handler for all button transitions | button |
Simpler dispatch, but less explicit |
| Gameplay movement from a stick | analogchange |
One coalesced callback per changed stick |
| Logic tied to individual X/Y axes | axischange |
Axis-level detail, but usually two callbacks per stick update |
| Detect when a stick starts/stops being used | grab / drop |
Low-frequency transition events |
For example, subscribing to buttondown and button and making both callbacks trigger jump() can fire duplicate gameplay work. Likewise, subscribing to both analogchange and axischange and writing movement from both will process one physical stick movement more than once. Pick the narrowest event family that covers the behavior.
Note: Event names are case agnostic - 'buttondown', 'ButtonDown', 'BUTTONDOWN' all work the same way.
The ButtonAction type defines the possible actions for the global button event:
'pressed' - Button was just pressed (transition from not pressed to pressed)'held' - A held button's reported value changed while it remained pressed; it is not emitted every polling frame when unchanged'released' - Button was just released (transition from pressed to not pressed)// Get controller type (automatically detected)
const type = controller.getType(); // 'Xbox', 'PS', 'NS', 'PC', 'Standard', 'Generic'
// Get human-readable name
const name = controller.getDisplayName(); // "Xbox Controller (Standard)"
// Check feature support
if (controller.hasHapticSupport()) {
console.log('Vibration supported');
}
if (controller.hasMotionSupport()) {
console.log('Motion sensors supported');
}
if (controller.hasTouchpadSupport()) {
console.log('Touchpad supported');
}
Dead zones prevent unwanted input from analog stick drift and small movements. Values below the threshold are treated as 0.
// Set global dead zone (default: 0.0 - no dead zone)
controller.setDeadZone(0.15); // 15% dead zone - ignores small movements
// Set separate dead zones for each analog stick
controller.setLeftAnalogDeadZone(0.1); // 10% for left stick
controller.setRightAnalogDeadZone(0.2); // 20% for right stick
// Get current dead zone values
const globalDeadZone = controller.getDeadZone();
const leftDeadZone = controller.getLeftAnalogDeadZone();
const rightDeadZone = controller.getRightAnalogDeadZone();
How it works:
0.0 = No dead zone (all movement detected)0.15 = 15% dead zone (ignores small movements, prevents drift)1.0 = Maximum dead zone (only full stick movement detected)// Get detailed analog stick information
const leftStick = controller.getLeftAnalogPosition();
console.log(leftStick);
// { x: 0.5, y: -0.3, magnitude: 0.58, angle: -0.64 }
const rightStick = controller.getRightAnalogPosition();
console.log(rightStick);
// { x: 0.0, y: 0.0, magnitude: 0.0, angle: 0.0 }
// Check if analog sticks are being used
if (controller.isLeftAnalogHeld()) {
console.log('Left stick is being used');
}
if (controller.isRightAnalogHeld()) {
console.log('Right stick is being used');
}
// Check if specific buttons are pressed
if (controller.isButtonPressed('A')) {
console.log('A button is pressed');
}
// Get all currently pressed buttons
const pressedButtons = controller.getPressed();
console.log('Pressed buttons:', pressedButtons); // ['A', 'LT', 'UP']
// Get reactive button states
const buttonStates = controller.getButtonStates();
console.log(buttonStates);
// { A: { pressed: true, value: 1.0 }, LT: { pressed: true, value: 0.7 }, ... }
// Get complete controller state
const state = controller.getState();
console.log(state);
// { type: 'Xbox', index: 0, buttons: {...}, analogs: {...}, deadZones: {...} }
Note: Button names are case agnostic - 'A', 'a', 'LB', 'lb' all work the same way.
// Use vibration presets
await controller.vibratePreset('light-tap');
await controller.vibratePreset('heavy-shake', 500); // With 500ms delay
// Custom vibration
await controller.vibrate('dual-rumble', 0, 1000, 0.5, 1.0);
// Parameters: type, startDelay, duration, weakMagnitude, strongMagnitude
// Complex vibration patterns
await controller.vibratePattern([
{ delay: 0, duration: 100, weak: 0.5, strong: 0.5 },
{ delay: 200, duration: 100, weak: 1.0, strong: 1.0 },
{ delay: 400, duration: 200, weak: 0.3, strong: 0.8 }
]);
// Stop all vibrations
controller.stopVibration();
Controller.VIBRATION_PRESETS = {
'light-tap': { duration: 50, weak: 0.3, strong: 0.3 },
'medium-rumble': { duration: 200, weak: 0.6, strong: 0.6 },
'heavy-shake': { duration: 400, weak: 1.0, strong: 1.0 },
'notification': { duration: 100, weak: 0.5, strong: 0.2 },
'damage': { duration: 150, weak: 0.8, strong: 1.0 }
};
Note: All preset names are case agnostic - 'light-tap', 'LIGHT-TAP', and 'Light-Tap' all work the same way.
PlayStation controllers automatically map to PlayStation button names:
| Method | Description | Returns |
|---|---|---|
getMainController() |
Get the main controller | Controller | null |
getController(index) |
Get controller by index | Controller | null |
getControllers() |
Get all controllers | Controller[] |
getControllersWithMetadata() |
Get controllers with metadata | Array<{controller, index, isMain, connectionOrder}> |
setMainController(index) |
Set main controller | boolean |
on(event, callback) |
Add event listener | GamepadManager |
| Method | Description | Returns |
|---|---|---|
getType() |
Get controller type | string |
getDisplayName() |
Get human-readable name | string |
hasHapticSupport() |
Check vibration support | boolean |
hasMotionSupport() |
Check motion sensor support | boolean |
hasTouchpadSupport() |
Check touchpad support | boolean |
setDeadZone(value) |
Set global dead zone | void |
setLeftAnalogDeadZone(value) |
Set left stick dead zone | void |
setRightAnalogDeadZone(value) |
Set right stick dead zone | void |
getDeadZone() |
Get global dead zone | number |
getLeftAnalogDeadZone() |
Get left stick dead zone | number |
getRightAnalogDeadZone() |
Get right stick dead zone | number |
getLeftAnalogPosition() |
Get left stick data | AnalogPosition |
getRightAnalogPosition() |
Get right stick data | AnalogPosition |
isLeftAnalogHeld() |
Check if left stick is used | boolean |
isRightAnalogHeld() |
Check if right stick is used | boolean |
isButtonPressed(button) |
Check if button is pressed | boolean |
getPressed() |
Get pressed buttons | string[] |
getButtonStates() |
Get button states | ButtonStates |
getAnalogStates() |
Get analog states | AnalogStates |
getState() |
Get complete state | ControllerState |
vibrate(type, delay, duration, weak, strong) |
Custom vibration | Promise<void> |
vibratePreset(preset, delay) |
Use vibration preset | Promise<void> |
vibratePattern(pattern) |
Complex vibration | Promise<void> |
stopVibration() |
Stop all vibrations | void |
addEventListener(event, callback, options) |
Add event listener | Controller |
removeEventListener(event, callback) |
Remove event listener | Controller |
Register these with GamepadManager.on(...):
| Event | Description | Parameters |
|---|---|---|
connect |
Controller connected | (controller: Controller) |
disconnect |
Controller disconnected | (controller: Controller) |
Register these with controller.addEventListener(...):
| Event | Description | Parameters |
|---|---|---|
button |
Unified button changes for this controller | (button: string, value: number, action: ButtonAction) |
buttondown |
Button initially pressed | (button: string, value: number) |
buttonpress |
Held button value changed | (button: string, value: number, repeat: boolean) |
buttonup |
Button released | (button: string, value: number) |
analogchange |
Coalesced stick position changed | (analog: 'LEFT' | 'RIGHT', position: AnalogPosition, repeat: boolean) |
axischange |
Analog axis changed | (axis: string, value: number, angle: number, repeat: boolean) |
grab |
Analog stick grabbed | (analog: string) |
drop |
Analog stick released | (analog: string) |
MIT License - see LICENSE for details.
Created by doubleactii