Event Objects!
Goals:
- Process information about events using event objects
- Explore the keypress and keyup events
Coding Snippets:
- Event listeners automatically pass information about each event to the event handler, in the form of an event object
- Access the event object by adding a single argument to the event handler. Common names for this argument are
e
,evt
, andevent
. - Event objects have many other properties besides
key
, some of which are explored below.
Math and Computer Concepts:
- The key event object's
keyCode
property provides a numeric value representing that key (similar to ASCII); theshiftKey
,metaKey
,ctrlKey
, andaltKey
properties use boolean values to record the status of modifier keys at the time of the event; and thetimeStamp
property records how many milliseconds elapsed since the program started when the event fires. keypress
differs fromkeydown
primarily in that the value of itskey
property is case sensitive. There are additional, more nuanced differences too, such as that the keypress event doesn't fire for keystrokes that don't produce visible output on the screen (e.g., shift or control ) and only keyup events fire for the delete key.
Activities:
Save each of the following in a folder called EventObjects.
- SingleBindingMover: Make use of the keydown event object to create a program that allows the user to control a sprite using arrow keys. This program should contain only one call to the
keydown
event binding function. - KeyEventNuances: Explore the differences between the keydown, keypress, and keyup events. Write a simple script that uses the three key event binding functions to report the
key
,keyCode
, andtimeStamp
properties. Code a TypingTest program that tests how many letters you can correctly type in a given amount of time. Use keypress events to facilitate verifying that the typist correctly types upper and lower case letters. Measure time elapsed using the event object's
timeStamp
property (do not useDate
objects).- Compose a Piano program using the
tone
function. Recall thattone
'A',2
causes the 'A' note to be played for two seconds; a subsequent call totone
'A',0
silences that note. Use a single call tokeydown
to bind keystrokes of the keys on your computer to calls totone
to play musical notes. Similarly, use a single call tokeyup
to bind the release of those keys to calls totone
to make the notes stop playing.