This week, we'll be working on a one-week exercise on inputs and outputs. You will pick one input and one output at random, and your task is to connect them together using HTML, CSS, and JavaScript. The connection should be meaningful, that is, some aspect of the input should be carried through to the output. For example, if you have the mousemove event, you could use the coordinates of the mouse as parameters to your output.
A good place to start would be to hook up your event listener in JavaScript and use console.log()
to inspect the event object metadata that is sent when your event happens.
For reference, have a look at the notes from week 5, where we reviewed JavaScript, and from week 8, where we applied JavaScript to CSS animations. Also look below for notes on the Event Object, which we saw in week 8.
When you're done, please link to the website from your homepage and submit that link on Canvas. This exercise is due next week.
By now we've seen a few examples of simple event binding - when x happens, do y. Sometimes it's not enough to just know that an event has happened - sometimes we want to know additional information about an event. For example, for a keypress
event, it's good to know that any key was pressed, but in reality I probably want to know which specific key the user pressed. Similarly, for a click
event, I might want to know where on the page the click happened. We can access this information with the event object.
The event object is an object that's passed in to our event handler as a parameter. It contains different information depending on the event type, for example, a mouse-based event is going to have different information than a keyboard-based event. The easiest way to inspect the event object is with console.log
:
document.addEventListener("mousemove", handleMouseMove)
function handleMouseMove(evt) {
console.log(evt)
}
First, notice how I've added a parameter called evt
to my function definition. This tells Javascript that my event handler accepts an event object. You can call it whatever you want, but most commonly you will see it called either e
or evt
.
Second, I pass evt
straight in to console.log
so we can see it. Open up the console on this page and move the mouse around to see how often that event gets triggered. Then click the triangle next to the logged event to expand the object and see all the event metadata we have access to. We have properties like pageX
and pageY
that tell us the coordinates of the mouse cursor. We have properties like target
that tell us which element our mouse was over when the event was triggered. We even have a property shiftKey
that tells us if the user was holding their shift key when the event was triggered. And the list goes on!
Here are some helpful event object parameters for your in-class exercise: