Course Content
Advanced JavaScript Mastery
Advanced JavaScript Mastery
The Event Object
Whenever an event occurs in JavaScript, an event
object is automatically passed to the event handler. This object contains important information about the event, such as the element that triggered it (target
), the type of event (type
), and methods to control the behavior of the event, like preventDefault()
and stopPropagation()
.
Accessing Event-Related Information
The event
object contains several useful properties and methods that allow you to access information about the event and interact with it.
target
The target
property refers to the element that triggered the event. It helps us determine which element was clicked, hovered, or interacted with.
index
index
index
event.target
is used to identify the specific button that was clicked, and its id
is displayed in the paragraph with the ID display
.
type
The type
property provides the type of event that occurred (e.g., click
, submit
, keydown
).
index
index
index
The event.type
is displayed in the paragraph for feedback, showing that a click
event has occurred. Also, when the button is clicked, the background color of the entire body is changed to lightblue
.
preventDefault() Method in the Event Object
The preventDefault()
method stops the default behavior of an element, such as stopping a link from navigating or preventing a form from submitting.
index
index
index
Here, preventDefault()
prevents the default action (navigating to a new page) when clicking the link. Instead, an alert is displayed.
Practical Example: Handling Form Submission and Event Object Usage
Let's validate a form, prevent submission if fields are empty, and display the form's data along with event-related information like the target
, type
, and how preventDefault()
prevents default form submission.
index
index
index
When the "Sign Up" form is submitted, an event listener intercepts the submission with event.preventDefault()
. If either the username or password field is empty, an error message is displayed; otherwise, a success message appears, showing the submitted username. Additionally, details about the event—such as type, form ID, and whether the default action was prevented—are displayed in a dedicated section. The form is then reset for further use.
Thanks for your feedback!