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
keydown
event binding function. - Pass
keydown
a 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
keydown
function.
Activities:
Save each of the following in a folder called KeyboardEvents.
-
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-color
property for the HTML <body> element easily using thejQuery
function.