Event Objects!
Goals:
- Process information about events using event objects
- Further explore keypress, keyup, and keydown 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
keyCodeproperty provides a numeric value representing that key (similar to ASCII); theshiftKey,metaKey,ctrlKey, andaltKeyproperties use boolean values to record the status of modifier keys at the time of the event; and thetimeStampproperty records how many milliseconds elapsed since the program started when the event fires. keypressdiffers fromkeydownprimarily in that the value of itskeyproperty 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 keydownevent 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, andtimeStampproperties. 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
timeStampproperty (do not useDateobjects).
Compose a Piano program using the tonefunction. Recall thattone'A',2causes the 'A' note to be played for two seconds; a subsequent call totone'A',0silences that note. Use a single call tokeydownto bind keystrokes of the keys on your computer to calls totoneto play musical notes. Similarly, use a single call tokeyupto bind the release of those keys to calls totoneto make the notes stop playing.

