4

I'm attempting to get the browser to report the status of my XBOX controller. However, it appears to become "stuck" after the first button press. What am I doing wrong?

<body>
    <script>
        var gamepad = false;
        var gamepadDIV = []

        window.addEventListener("gamepadconnected", function(e) {
            gamepad = e.gamepad;

            for (i = 0; i < gamepad.buttons.length + gamepad.axes.length; i++) {
                gamepadDIV.push(document.createElement('div'));
                document.body.appendChild(gamepadDIV[i]);
            }

        });

        window.addEventListener("gamepaddisconnected", function() {
            gamepad = false;
        });


        function animation() {

            if (gamepad != false) {

                for (i = 0; i < gamepad.buttons.length; i++) {
                    gamepadDIV[i].innerHTML = gamepad.buttons[i].pressed;
                }

                for (i = gamepad.buttons.length; i < gamepad.buttons.length + gamepad.axes.length; i++) {
                    gamepadDIV[i].innerHTML = gamepad.axes[i - gamepad.buttons.length].value;
                }

            }

            window.requestAnimationFrame(animation);
        }
        animation();

    </script>
</body>
3
  • Code works fine for me as-is: jsfiddle.net/khrismuc/rnz5f6vg
    – user5734311
    May 25, 2020 at 10:23
  • Are you using FireFox? Because I just tested it in there, and like you said it works fine. Using Chrome or the latest Microsoft Edge however, it sticks on the first button and never changes. Are you having the same issue, or is it unique to my setup? May 25, 2020 at 13:28
  • You're right, it doesn't work in Chrome at all.
    – user5734311
    May 25, 2020 at 16:06

1 Answer 1

4

I ran into the same issue with Chrome too.

Basically Chrome doesn't update the Gamepad object as state changes. Instead you have to poll it for updated state.

In one of the tutorials on MDN you'll see this this line:

var gamepads = navigator.getGamepads 
    ? navigator.getGamepads() 
    : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : [])

So basically as I understand it, you can use the gamepadconnected event to handle initialization logic but after that you can't reference the object directly to get state changes.

You can find more about that here: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.