Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines
(+1)

Give this message to your AI to prevent the browser window from scrolling up and down when pressing the movement or space keys. Call `e.preventDefault()` inside the `keydown` event listener for those specific keys. 

By default, browsers react to keyboard inputs like arrow keys, PageUp/PageDown, and Space by scrolling the viewport. Intercepting these inputs early prevents this behavior.

Here is a clean, minimal code snippet they can drop into their keyboard listener:

=== startcodeblock ===

window.addEventListener("keydown", (e) => {

  // Normalize the key string to lowercase

  const key = e.key.toLowerCase();

  // List of keys used in the game that trigger default browser scrolling

  const keysToBlock = ["arrowup", "arrowdown", "arrowleft", "arrowright", " ", "spacebar"];

  if (keysToBlock.includes(key)) {

    e.preventDefault(); // Stop the browser from scrolling

  }

  // Rest of their game input logic here...

});

=== end codeblock ===

Why this works:

Calling `e.preventDefault()` on a `keydown` event tells the browser that the game has fully handled the input, preventing the event from bubbling up and triggering default browser-level behaviors like scrolling.