how to listen for inputs from external sources in javascript

In order to listen for inputs from external sources in JavaScript, we can use event listeners and input devices such as gamepads or touchscreens, and also through websockets.

Event Listeners

We can listen for input events using standard event listeners in our JavaScript code. For example, we can listen for a button click like this:

index.tsx
const button = document.querySelector('#my-button');
button.addEventListener('click', function() {
  console.log('button clicked!');
});
137 chars
5 lines

External Input Devices

We can listen for input from external devices, such as gamepads or touchscreens, using the Gamepad API and Touch Events API. For example, we can listen for button presses on a gamepad like this:

index.tsx
window.addEventListener('gamepadconnected', function(e) {
  const gamepad = navigator.getGamepads()[e.gamepad.index];
  console.log('connected', gamepad);

  const buttonIndex = 0;
  setInterval(function() {
    if (gamepad.buttons[buttonIndex].pressed) {
      console.log('button pressed!');
    }
  }, 10);
});
314 chars
12 lines

Websockets

We can also listen for input from external sources using Websockets. Websockets allow for real-time data transfer between a client and a server. For example, we can set up a Websocket connection in our JavaScript code like this:

index.tsx
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = function() {
  console.log('websocket connection established');
};
socket.onmessage = function(event) {
  const message = event.data;
  console.log('received:', message);
};
243 chars
9 lines

Once we have set up a WebSocket connection, we can send and receive data as needed.

gistlibby LogSnag