Event-Based Implementation HTML5 Gamepad API

HTML5 introduced most of the components needed for rich and interactive game development. With JavaScript applications, technologies such as canvas tag, WebGL, an audio tag, and video tag have matured to the point where they can now support many tasks that previously required local code. The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers.

What Is the Gamepad API?

Simply put, the Gamepad API allows you to interact with your browser using a video game console controller, also known as a gamepad.

In Chrome browser implementations, this Gamepad API introduces new events to the window object to read the status of the gamepad. In addition to these events, the API adds a Gamepad object that you can use to query the status of a connected gamepad and a navigator.getGamepads() method that you can use to get a list of connected gamepads on the page.

This means you can know the state of the gamepad, you can know if buttons are pressed or not but you have to ask every time. API returns the state when being asked, instead of firing events when things change.

This is not enough for me to enjoy this API, So jumped in and prepared a jQuery gamepad-events plugin for myself to improve development quality. I needed event-based button change detection for some use cases I had while developing a fun browser game for an event.

Firing Events for Gamepad Buttons

I relied on requestAnimationFrame() to set up polling in the most efficient and battery-friendly way. The script starts a polling loop to check for gamepad state. It checks for the gamepad status, monitors the necessary data and notices the differences from the previous state. If differences are noticed, raises proper event about button presses and joystick changes. Supported events are gamepadpressdown, gamepadpressup, gamepadaxismove for now.

Using gamepad-events script

Script simply should be included in html page.

	<head>
		<script src='gamepad-events.js'></script>
	</head>

Gamepad events can be listened by javascript or jQuery if wanted.

document.addEventListener("gamepadconnected", function(e) {
  console.log(e);
});

document.addEventListener("gamepaddisconnected", function(e) {
  console.log(e);
});

document.addEventListener("gamepadpressdown", function(e){
  console.log(e);
});

document.addEventListener("gamepadpressup", function(e){
  console.log(e);
});

document.addEventListener("gamepadaxismove", function(e){
  console.log(e);
});

Just connect your controller and press any button.

Thank you for taking the time to learn about the Gamepad API and my javascript plugin. For more information; Gamepad API page has detailed information about the Gamepad API including experimental features and jQuery gamepad-events plugin page some information about my implementation of Gamepad API. I hope this helps/inspires some good projects.