- read

Playing with the GamePad API

Alvaro Montoro 57

Playing with the GamePad API

My journey programming with the GamePad API with detailed explanations and code to get JavaScript games ready to use controllers on the browser

Alvaro Montoro
Level Up Coding
Published in
12 min read15 hours ago


Photo by Patrick on Unsplash

I am not a gamer. Maybe I was at once in my life, but not anymore. Even then, I was not that great of a player. But two things happened that encouraged me to start using gamepads on my computer. The first was the nostalgia of playing 90s/early 2000s video games, which drove me to purchase a set with a Raspberry Pi, a case, and a few controllers. Building a RetroPie became a personal project.

The second one was an afternoon of “boredom.” I wanted to develop, but I was running out of ideas. So, I decided to explore something new. I navigated to the Web APIs page on MDN, and something caught my eye on the letter g: Gamepad API.

Curiosity killed the cat…

A standard API to access and control gamepads? And supported by all major browsers even when listed as “experimental?” Unexpected…but interesting. It caught my attention and my curiosity.

I had a computer, a game controller, JavaScript knowledge, and a few spare hours… What did I have to lose?

After reading the first page, it looked simple: it only had a handful of interfaces, events, and methods to play with. Nothing that I couldn’t handle…or so I thought. I jumped to the MDN tutorial and simplified the first code example a little:

window.addEventListener("gamepadconnected", function() {
console.log("Gamepad Connected");

A bit of theory: The gamepadconnected event is triggered when a gamepad is connected to the browser. Similarly, there is a gamepaddisconnected event that is triggered when a gamepad is disconnected. And with this paragraph, you’ve learned about the only two events available on the API. Now back to our story.

The page loaded on the browser, and I giddily plugged the RetroPie controller into my computer and…


Unplugged the gamepad. Replugged it, and…


Unplugged. Replugged.