# How Typing Game Keyboard Event Handling Works in Microsoft's Web Dev Tutorial

> Learn how the typing game in Microsoft's Web Dev tutorial handles keyboard events. Discover real-time feedback and game advancement on every keystroke. Perfect for beginners.

- Repository: [Microsoft/Web-Dev-For-Beginners](https://github.com/microsoft/Web-Dev-For-Beginners)
- Tags: how-to-guide
- Published: 2026-02-27

---

**The typing game uses a single `input` event listener on the text field to detect every keystroke, comparing the growing string against the target word in real-time to provide immediate feedback and advance the game when a space is typed.**

The Microsoft Web-Dev-For-Beginners repository includes an educational typing game that demonstrates modern ES6 JavaScript patterns for capturing user input. Unlike traditional approaches that rely on low-level `keydown` or `keypress` events, this implementation leverages the standard **`input`** event to handle typing game keyboard event handling in a way that supports both physical keyboards and on-screen mobile keyboards. This architecture automatically filters out non-character keys like arrows and Shift while working seamlessly across devices.

## Why the Input Event Outperforms Keyboard Events

The solution in [`4-typing-game/solution/index.js`](https://github.com/microsoft/Web-Dev-For-Beginners/blob/main/4-typing-game/solution/index.js) deliberately avoids `keydown` and `keypress` events. Instead, it attaches a single listener to the input element:

```javascript
// Line 90-92 in index.js
typedValueElement.addEventListener("input", handleTyping);

```

This approach offers three distinct advantages for typing game keyboard event handling:

- **Automatic filtering**: The `input` event only fires when the actual value of the field changes, ignoring modifier keys (Ctrl, Alt, Shift) and navigation keys (arrows, Home, End) that do not alter text content.
- **Mobile compatibility**: On-screen keyboards on touch devices generate `input` events consistently, whereas `keydown` behavior varies across platforms.
- **Simplified validation**: The handler reads the complete current value of the input rather than processing individual key codes, making string comparison straightforward.

## Setting Up the Game State

Before handling keyboard input, the script caches references to DOM elements and initializes the game state.

### Caching UI Elements

At lines 20–24 in [`index.js`](https://github.com/microsoft/Web-Dev-For-Beginners/blob/main/index.js), the script stores references to the quote container, message area, text input, and start button:

```javascript
const quoteElement = document.querySelector("#quote");
const messageElement = document.querySelector("#message");
const typedValueElement = document.querySelector("#typed-value");
const startButton = document.getElementById("start");

```

These references allow the event handlers to update the UI without re-querying the DOM on every keystroke.

### Initializing the Game

When the user clicks the **Start** button, the `startGame()` function (lines 50–63) prepares the game state:

- Selects a random quote and splits it into a `words` array
- Resets `wordIndex` to zero
- Renders the quote as a series of `<span>` elements for individual word styling
- Clears previous messages and focuses the input field
- Records the start timestamp with `new Date().getTime()`

```javascript
startButton.addEventListener("click", startGame);

```

## Real-Time Validation Logic

The core of the typing game keyboard event handling resides in the `handleTyping()` function (lines 66–86). This function executes on every `input` event and implements a three-tier validation system.

### Detecting Game Completion

First, the code checks if the user has typed the exact final word (lines 69–74):

```javascript
const currentWord = words[wordIndex];
const typedValue = typedValueElement.value;

if (typedValue === currentWord && wordIndex === words.length - 1) {
  const elapsedTime = new Date().getTime() - startTime;
  const message = `CONGRATULATIONS! You finished in ${elapsedTime / 1000} seconds.`;
  messageElement.innerText = message;
  typedValueElement.disabled = true;
  startButton.disabled = false;
}

```

When the typed value matches the current word and the index points to the last element in the array, the game ends, calculates elapsed time, and disables further input.

### Advancing Between Words

If the game has not ended, the handler checks for word completion using a trailing space (lines 75–79):

```javascript
else if (typedValue.endsWith(" ") && typedValue.trim() === currentWord) {
  typedValueElement.value = "";
  wordIndex++;
  highlightWord(wordIndex);
}

```

When the user types a space after a correct word, the input clears, the `wordIndex` increments, and the `highlightWord()` helper updates the visual marker to the next word.

### Character-by-Character Validation

For incomplete words, the script validates the prefix in real-time (lines 80–86):

```javascript
else if (currentWord.startsWith(typedValue)) {
  typedValueElement.className = "";
  messageElement.innerText = "";
} else {
  typedValueElement.className = "error";
  messageElement.innerText = "Incorrect letter!";
}

```

If the current word starts with the typed value, the error state clears. Otherwise, the script applies an `error` class to the input field and displays a warning message.

## Providing Visual Feedback

The `highlightWord()` function (lines 45–48) manages the visual indicator showing which word the user should type next:

```javascript
function highlightWord(index) {
  const spans = quoteElement.querySelectorAll("span");
  spans.forEach((span, i) => {
    span.className = i === index ? "highlight" : "";
  });
}

```

This helper toggles the `highlight` class on the appropriate `<span>` element, ensuring the user always knows their position in the quote.

## Summary

- The typing game attaches a single **`input`** event listener to the text field rather than using `keydown` or `keypress` events.
- The `handleTyping()` function in [`4-typing-game/solution/index.js`](https://github.com/microsoft/Web-Dev-For-Beginners/blob/main/4-typing-game/solution/index.js) compares the input value against the target word array on every keystroke.
- Validation occurs in three stages: checking for game completion (last word), detecting word boundaries (trailing space), and real-time character matching (`startsWith`).
- The approach naturally supports mobile keyboards and ignores non-printing keys since the `input` event only fires when the field's value actually changes.

## Frequently Asked Questions

### Why does the typing game use the input event instead of keydown?

According to the source code in `microsoft/Web-Dev-For-Beginners`, the **`input`** event provides a higher-level abstraction that fires whenever the input's value changes, regardless of how that change occurred. This eliminates the need to filter out modifier keys, arrow keys, and function keys manually, and ensures compatibility with mobile on-screen keyboards that may not fire traditional keyboard events consistently.

### How does the game detect when a word is finished?

The game checks if the typed value `endsWith(" ")` (a trailing space) and if `typedValue.trim()` equals the `currentWord` exactly. When both conditions match, the script clears the input field, increments the `wordIndex`, and calls `highlightWord()` to move the visual indicator to the next word (lines 75–79 in [`index.js`](https://github.com/microsoft/Web-Dev-For-Beginners/blob/main/index.js)).

### What happens when the user makes a typing error?

When the typed value is not a prefix of the current target word (fails the `currentWord.startsWith(typedValue)` check), the script adds an `error` class to the input element and displays "Incorrect letter!" in the message area. Once the user corrects the input to match the beginning of the target word, the error styling clears automatically (lines 80–86).

### Does this keyboard handling approach work on mobile devices?

Yes. The `input` event is part of the standard DOM specification and fires consistently across mobile browsers when users type on virtual keyboards. This is superior to `keydown` events, which behave inconsistently or may not fire at all on certain mobile platforms, making the typing game keyboard event handling robust for cross-device usage.