Category:Events

Triggers a sequence of blocks to run when a specified key is pressed.

Sometimes code should only be run if an event happens. In this case, when a specified key on the keyboard is pressed, the blocks attached under the event block will begin to run sequentially.

This block has a drop-down menu with “when” and “while” options. “When” a key is pressed, the code will only run once. “While” a key is pressed, the code will run over and over again until the key stops being pressed.

Examples

Example 1

This block is most often used to control a sprite’s movement using the arrow keys.

Example 2

Compare the use of “when” and “while.” The bunny will only move 10 pixels up or down when the corresponding arrows are pressed. However it will continuously move 10 pixels east and west while the corresponding arrows are pressed.

Example 3

Nearly any key can be pressed as an event. In this example, each key triggers a different action.

Parameters

NameDescription
when/while Determines if the code is run when the key is pressed (runs once at a time) or continuously while the key is pressed
key Which key triggers the event

Found a bug in the documentation? Let us know at documentation@code.org