Mouse Events!
Goals:
- Make programs responsive to clicks and other mouse-related events
- Attach listeners to specific page elements or collections of elements
Coding Snippets:
turtle.click
attaches an event listener to the default turtle's HTML page element. That listener executes the event handlerrCB
each time that sprite is clicked.$('.turtle').click
attaches event listeners to all page elements with class attributeturtle
, i.e., all sprites.click
(alias forwindow.click
) binds the event handlerallCB
to the page's <html> element. The handler is executed with a click anywhere on the page, i.e., with every click.- The event object (e.g.,
e
) provides useful details about the event. Especially useful is thetarget
property, which identifies the specific page element that was clicked.
Math and Computer Concepts:
- All event listeners are associated with specific page elements. In Pencil Code, the default association is with the
window
object. For example, the jQuery methodkeydown
is actually an alias forwindow.keydown
. This default works well for most key-related events, because as long as the page is selected, all keystrokes have the potential to fire off events.
- With mouse-related events one must be more deliberate about which page elements to bind to event handlers. In the examples above,
turtle.click
creates a listener for clicks on the default turtle and$(".turtle")
adds listeners for clicks on any sprite. - Frequently we want the event handler to specifically reference the element that has been clicked. The event object's
target
property always identifies that page element.$(e.target)
provides a jQuery object that we can interact with as we would any sprite.
Activities:
Save each of the following in a folder called MouseEvents.
- Hopper: use events to make the default turtle hop every time you click it. Use the event object's
target
property to make it hop in the direction of the mouse, i.e., if you click on it near its head, it should hop forward, and if you click near its tail, it should turn and hop in the other direction. To complete this task, make the hop look like a hop, i.e., come up with an algorithm that make the turtle appear to grow during the first half of its forward motion, as it gains altitude, and then have it return to normal size on it's way back down. - Hoppers: copy your Hopper program and modify it so that there are 20 or more turtles (you might use
hatch
to simplify that part), each of which hops (and perhaps changes color) when you click it. - There are numerous other mouse-related events. For this activity, make use of the
mousemove
event binding function to create a sprite (or sprites) with MovingEyes. Perhaps begin by important an image of an animal or person. Add sprites for each eye, and bind events so that the eyes follow the position of the mouse on the screen.