What is the Event
object?
The Event
object is a payload that triggers when a user interacts with your web page in some way. These interactions can be anything from clicking on a button or focusing an input to shaking their mobile device.
Like all JavaScript objects, the Event
object has a number of properties that might be helpful. The properties available depend on the event that triggered this payload.
All Event
objects will have the type
property. This property reveals the type of event that triggered the payload, such as "keydown"
or "click"
. These values will correspond to the same values you might pass to addEventListener(), where you can capture and utilize the Event
object.
Event
objects will always have the target
property. The target
property is a reference to whatever object triggered the event. Most commonly, this will be some sort of HTMLElement
object, or the Document
or Window
objects. But it can also be something more specific, like an AudioContext
.
Events also have methods, which are functions exposed as properties on the object. One commonly used method is preventDefault()
, which prevents the default behavior of the event when called.
If you want to handle form submissions yourself, for example, you might call preventDefault()
to keep the browser from trying to submit the form data as a POST
request. You will learn more about POST
requests in future lecture videos.
You’ll also likely run in to the stopPropagation()
method. This method prevents the event from bubbling up or propagating to parent elements. You’ll learn more about what this means in a later lecture.
There are also a large number of properties that are specific to certain implementations of the Event
object. For example, a FetchEvent
will have a request property to contain the request that triggered the event.
If you are ever unsure of what properties are available, you can log the Event
object in question or even check the documentation.
Inline Event Handlers DOMContentLoaded setTimeout() & setInterval() Event bubbling & delegation