Keyboard Events!
Goals:
- Make programs interactive by accepting keyboard input
- Learn about events and event listeners
Coding Snippets:
- Instruct javascript to bind key presses to predefined callback functions using the
keydownevent binding function. - Pass
keydowna string specifying which key to listen for (e.g., "a", "up", "space") and a callback specifying the action to take - With each key press, JavaScript will invoke the associated callback.
Math and Computer Concepts:
- Web browsers continuously communicate with the computer operating system to allow pages to react to changes in the state of the computer. Browsers use a special type of object called events to indicate that something of potential interest has occured.
- Events "fire" when the page loads, when a window is resized or closed, when the mouse is moved, when user clicks a button, when a key is pressed, etc.
- To make your program react to events, create an event listener for a specific type of event using an event binding function, such as the
keydownfunction.
Activities:
Save each of the following in a folder called KeyboardEvents.
-
Make a EtchATurtleSketch program that allows the user move the turtle around the screen using the arrow keys ("up", "down", "right", "left"). Begin by defining callback functions that provide instructions that should be carried out when each specific key is pressed. Then bind the callbacks to the desired keys using
keydown. - TurtleCannon: Get started on your very own shoot-em-up game by coding a sprite that functions as a cannon. Bind the left and right arrow keys to functions to aim the cannon and bind the space key to a function that launches a projectile (i.e., a sprite, potentially with the image of a cannonball, a fireball, a missile, a turtle... coder's choice!) that flies across the screen. (In a later lesson, we will continue to work on this program, adding targets and a scoreboard as well.)
- ToggleColor: Write a script that lets you change the background color at any time while your script is running by pressing the key corresponding to the first letter of that color (e.g., b for blue). Hint: recall that you can change the background color by updating the CSS
background-colorproperty for the HTML <body> element easily using thejQueryfunction.


