event.type: Identifying Which Event Occurred
You'll learn how to use the event.type property to determine exactly which type of event triggered your handler function.
The Core Idea
When an event handler function runs, the Event Object it receives contains a property called type. This property is a string that tells you the name of the event that occurred—like "click", "keydown", "submit", or any other event type you've learned so far.
This is especially useful when you attach the same handler function to multiple different event types and need to know which one actually fired.
Why It Matters
Think of event.type like caller ID on your phone. When your phone rings, you want to know who's calling before you answer. Similarly, when your handler function runs, event.type tells you which event is calling.
Using event.type
function handleEvent(event) {
console.log("Event type:", event.type);
if (event.type === "click") {
console.log("User clicked!");
} else if (event.type === "mouseenter") {
console.log("Mouse entered!");
}
}
const button = document.querySelector("button");
button.addEventListener("click", handleEvent);
button.addEventListener("mouseenter", handleEvent);
In this example, the same handleEvent function responds to both click and mouseenter events. Inside the function, event.type tells us which one occurred, so we can respond appropriately.
Common Use Case
You might use event.type when handling multiple keyboard events with one function, or when debugging to see what events are firing on an element.
Key Takeaway: The event.type property returns a string identifying which event triggered your handler, enabling one function to handle multiple event types intelligently.