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.
Example of Event Handlers
Basic HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button class="button">Click me!</button>
</body>
</html>
Selecting Elements to Attach Events:
Before you can respond to user actions, you need to select the HTML element in JavaScript.
You can use document.querySelector()
or any other DOM selection method:
const button = document.querySelector(".button");
Learn more about JavaScript DOM selection methods!
Attaching Event Listeners:
The main way to listen for events is with addEventListener()
.
Syntax:
element.addEventListener(eventType, eventHandlerFunction);
Here,
eventType
is a string like"click"
,"mouseover"
,"keydown"
, etc.eventHandlerFunction
is the function that runs when the event happens.
What Happens Behind the Scenes?
addEventListener
does not block your page. It sets up the listener and lets the browser wait for the event.- When the event happens, the browser calls your function.
- You can attach multiple event listeners of different types to the same element.
Let's understand event listeners with some examples.
Example 1:
const button = document.querySelector(".btn");
button.addEventListener("click", () => {
alert("I'm clicked!");
});
Here,
const button = document.querySelector(".btn");
finds the first HTML element with the classbtn
and stores that element in a variable calledbutton
.button.addEventListener("click", () => {...});
tells the browser, "When someone clicks this button, run the code inside the function."- The function shows an alert that says, "I'm clicked!"
Example 2:
const button = document.querySelector(".btn");
button.addEventListener("mouseover", () => {
button.style.color = "red";
});
Here,
const button = document.querySelector(".btn");
finds the first HTML element with the classbtn
and stores that element in a variable calledbutton
.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
.
For example:
button.addEventListener("click", (event) => {
console.log("Clicked element:", event.target);
});
Here,
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.");
});
Example 2: Logging Mouse Position on Click
button.addEventListener("click", (event) => {
console.log("X:", event.clientX, "Y:", event.clientY);
});
Removing Event Listeners
Remember to remove event listeners if you no longer need them. To remove them, you can use removeEventListener()
to remove an event.
For example:
function handleClick() {
alert("Clicked!");
}
button.addEventListener("click", handleClick);
// Later, remove the event listener:
button.removeEventListener("click", handleClick);
Common JavaScript Event Types
Here are the most commonly used event types:
Mouse Events
These happen when the user interacts with the mouse.
Event | When It Happens | Example Use Case |
---|---|---|
click |
When the user clicks on an element | Button click |
dblclick |
When the user double-clicks | Double-click to edit text |
mouseover |
When the mouse pointer enters an element | Highlight an item |
mouseout |
When the mouse pointer leaves an element | Remove highlight |
mousedown |
When a mouse button is pressed down | Start dragging |
mouseup |
When a mouse button is released | Drop item after dragging |
mousemove |
When the mouse moves over an element | Drawing on a canvas |
Keyboard Events
These happen when the user presses keys on the keyboard.
Event | When It Happens | Example Use Case |
---|---|---|
keydown |
When a key is pressed down | Detect shortcuts like Ctrl+S |
keyup |
When a key is released | Validate input after typing |
keypress |
When a key is pressed (deprecated) | Older event for key presses (use keydown instead) |
Form Events
Events related to forms and input elements.
Event | When It Happens | Example Use Case |
---|---|---|
submit |
When a form is submitted | Validate form before sending |
change |
When the value of an input changes and loses focus | Detect option selected |
input |
When the value of an input changes (immediately) | Live search/filtering |
focus |
When an input gains focus | Highlight input field |
blur |
When an input loses focus | Validate field after typing |
Window Events
Events related to the browser window.
Event | When It Happens | Example Use Case |
---|---|---|
load |
When the page and all resources finish loading | Show loading spinner |
resize |
When the browser window is resized | Adjust layout responsively |
scroll |
When the user scrolls the page | Lazy load images or sticky nav |
beforeunload |
When the user tries to leave the page | Confirm before closing tab |
Media Events
Events related to audio and video playback.
Event | When It Happens | Example Use Case |
---|---|---|
play |
When media playback starts | Show pause button |
pause |
When media playback pauses | Show play button |
ended |
When media playback ends | Show replay button |
timeupdate |
When playback position changes | Update progress bar |
Clipboard Events
Events related to copying and pasting.
Event | When It Happens | Example Use Case |
---|---|---|
copy |
When content is copied | Modify copied text |
cut |
When content is cut | Custom cut behavior |
paste |
When content is pasted | Clean pasted input |
Drag & Drop Events
Used to create drag-and-drop interfaces.
Event | When It Happens | Example Use Case |
---|---|---|
dragstart |
When dragging starts | Show drag preview |
drag |
When the item is being dragged | Update UI |
dragover |
When dragged item is over a drop zone | Highlight drop target |
drop |
When the item is dropped | Handle drop action |
dragend |
When dragging ends | Clean up UI |
Touch Events (for mobile devices)
These events handle touch interactions on phones and tablets.
Event | When It Happens | Example Use Case |
---|---|---|
touchstart |
When a finger touches the screen | Detect tap |
touchmove |
When a finger moves on the screen | Swipe gestures |
touchend |
When a finger is lifted off screen | End of swipe or tap |