Workshop › 15 Puzzle › Step 15 of 27
The arrow keys feel best when they move a tile towards the gap: Left slides the tile on the right of the gap to the left. A small lookup object says where that tile is.
```js
// An arrow moves the tile on the other side of the gap in that direction: Left slides the tile right of the gap to the left.
document.addEventListener('keydown', (event) => {
const gap = tiles.indexOf(0)
const from = { ArrowLeft: 1, ArrowRight: -1, ArrowUp: N, ArrowDown: -N }[event.key]
if (from !== undefined) {
event.preventDefault()
if (neighbors(gap).includes(gap + from)) move(gap + from)
}
})
```keydown fires when a key goes down; event.key is its name, such as 'ArrowLeft'.{ ArrowLeft: 1, ... } is read with [event.key]: for Left it gives 1, for any other key undefined.event.preventDefault() stops the arrows from scrolling the page.gap + from is the tile to move; the neighbour check stops it from wrapping to another row.Above function squareX(i), write the comment and the listener, and leave an empty line. Press Run and try the
arrows.
Skills: Keyboard and mouse input
← Click a tile Count the moves →