Learn how to handle user actions in JavaScript with events. Learn about event listeners, common event types, and how to respond to clicks, keyboard input, and more.
Loading...
Events: How to Handle User Actions
By using JavaScript events, you can control how your webpage responds to user actions, like clicks, mouse movements, keyboard presses, and more.
What Are Events?
On a webpage:
Clicking a button
Moving the mouse
Pressing a key
Submitting a form
Loading a page
All of these actions or occurrences that happen in the browser are events.
When an event happens, you can tell JavaScript to listen for this event and run code when it happens. You can do this by using event handlers.
const button = document.querySelector(".btn"); finds the first HTML element with the class btn and stores that element in a variable called button.
button.addEventListener("mouseover", () => {...}); tells the browser, "When the mouse pointer moves over this button, run the code inside the function."
The function changes the text color of the button to red.
The Event Object
Whenever an event occurs (like a click, keypress, or mouse move), JavaScript automatically creates an event object and passes it into the function handling that event.
This object contains all the details about the event, such as:
What type of event happened (click, input, keydown, etc)
Which element triggered it
Where it happened (mouse position)
What keys or buttons were pressed
...and much more.
You can access this object by adding a parameter to your event handler function. It’s usually named event, e, or evt.
event is the object that holds info about the click.
event.target tells you which element was actually clicked. It's useful if you have multiple buttons or nested elements.
console.log(...) shows the element in the browser’s console.
What Can You Do With the Event Object?
Here are some useful properties of the event object:
Property
What It Tells You
event.type
The type of event ("click", "keydown", etc.)
event.target
The exact element that triggered the event
event.clientX / clientY
Mouse pointer’s X/Y position in the viewport
event.key
The key that was pressed (for keyboard events)
event.preventDefault()
Stops the default browser behavior (like stopping form submit)
Example of Event Object
Example 1: Preventing a Link from Redirecting
const link = document.querySelector("a");link.addEventListener("click", (event) => { event.preventDefault(); // stops the link from navigating console.log("Link clicked, but not redirected.");});