JavaScript Events
Reviewed & published by Brayan K
Learn how to make your web pages come alive by responding to user interactions like clicks, key presses, and form submissions.
Part of the free JavaScript course at LearnCodingFast โ hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- What events are and why they matter
- Add listeners with addEventListener()
- Handle mouse, keyboard, and form events
- Use the event object for details
- Stop default browser behaviour
- Build interactive UI with event handling
๐ก Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
๐ฏ Real-World Analogy: Events are like a hotel receptionist:
- โข The receptionist listens for guests arriving (event listener)
- โข When a guest arrives, they respond appropriately (event handler)
- โข Different actions require different responses (click vs. hover vs. type)
๐ง What Are Events?
An event is an action that occurs in the browser.
| Event Type | When It Fires | Common Use |
|---|---|---|
| click | User clicks element | Buttons, links, cards |
| keydown | User presses a key | Keyboard shortcuts, games |
| submit | Form is submitted | Login, search forms |
| mouseover | Mouse hovers element | Tooltips, previews |
JavaScript allows you to listen for these events and respond to them โ this is called event handling.
๐ก Without events, your web pages would be static and non-interactive.
โ๏ธ Example: Simple Click Event
<button id="clickMe">Click Me!</button>const button = document.getElementById("clickMe");
button.addEventListener("click", () => {
console.log("Button clicked!");
});Button clicked!This is the basic pattern of all JavaScript interactivity โ select โ listen โ respond.
๐งฉ Adding Event Listeners
The modern and most reliable way to handle events is with addEventListener().
๐ Syntax:
element.addEventListener(eventType, function);๐ง Example: Button Click
button.addEventListener("click", function() {
console.log("You clicked the button!");
});Or using arrow functions (modern ES6 style):
button.addEventListener("click", () => {
console.log("You clicked the button!");
});๐ฑ๏ธ Mouse Events
Mouse events are triggered when the user interacts with the mouse.
Here are the most common ones:
| Event | Description |
|---|---|
| click | When the element is clicked |
| dblclick | Double-click event |
| mouseenter | When the cursor enters the element |
| mouseleave | When the cursor leaves the element |
| mousemove | Fires repeatedly as the mouse moves |
๐งฉ Example:
<button id="mouseBtn">Hover or Click</button>const btn = document.getElementById("mouseBtn");
btn.addEventListener("click", () => console.log("Clicked!"));
btn.addEventListener("dblclick", () => console.log("Double-clicked!"));
btn.addEventListener("mouseenter", () => console.log("Mouse entered!"));
btn.addEventListener("mouseleave", () => console.log("Mouse left!"));Mouse entered!
Clicked!
Mouse left!โจ๏ธ Keyboard Events
Keyboard events happen when users press keys on their keyboard.
They're often used in forms, games, or shortcuts.
| Event | Description |
|---|---|
| keydown | Fires when a key is pressed down |
| keyup | Fires when a key is released |
| keypress | Deprecated โ use keydown instead |
Example:
document.addEventListener("keydown", (event) => {
console.log("Key pressed:", event.key);
});
document.addEventListener("keyup", (event) => {
console.log("Key released:", event.key);
});Key pressed: a
Key released: a๐งพ Form Events
Forms have their own events โ they're essential for validating input and handling data without refreshing the page.
| Event | Description |
|---|---|
| submit | Triggered when form is submitted |
| input | Fires while the user is typing |
| change | Fires when an input value changes (after losing focus) |
| focus | When an input gets focus |
| blur | When an input loses focus |
๐ก Example: Prevent Default Submission
<form id="userForm">
<input type="text" placeholder="Enter name" id="nameInput" />
<button type="submit">Submit</button>
</form>const form = document.getElementById("userForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevents form refresh
console.log("Form submitted!");
});Form submitted!๐ก Always use event.preventDefault() when handling form data in JavaScript โ it stops the browser from reloading the page.
Example: Input Events
const input = document.getElementById("nameInput");
input.addEventListener("input", () => {
console.log("Value changed:", input.value);
});Value changed: BrayanEvery keystroke triggers the event in real time.
๐ง The Event Object
Whenever an event happens, JavaScript automatically passes an event object to the callback function.
It contains details about the event, like:
- โข The element that triggered it (event.target)
- โข The event type (event.type)
- โข Mouse position, pressed key, etc.
document.addEventListener("click", (event) => {
console.log("Clicked element:", event.target);
console.log("Event type:", event.type);
});Clicked element: <button id="mouseBtn">Hover or Click</button>
Event type: clickExample: Stopping Default Behavior
Some elements (like links or forms) have default behaviors.
You can stop those actions using event.preventDefault().
<a href="https://google.com" id="link">Go to Google</a>const link = document.getElementById("link");
link.addEventListener("click", (event) => {
event.preventDefault();
console.log("Default action stopped!");
});๐ข Result: The link won't open, but the message will appear in the console.
๐ฎ Interactive Example โ Key Tracker
Let's create a simple program that displays which key the user pressed.
<h2>Press any key!</h2>
<p id="displayKey">Waiting for input...</p>๐ข Output (on the page):
You pressed: a๐งฉ Example โ Change Background on Click
<button id="colorBtn">Change Background</button>const colorBtn = document.getElementById("colorBtn");
colorBtn.addEventListener("click", () => {
document.body.style.backgroundColor =
document.body.style.backgroundColor === "lightblue"
? "white"
: "lightblue";
});๐ข Result: The background toggles each time you click the button!
โ๏ธ Window Events
The window object represents the browser window itself.
You can detect changes like loading, resizing, or scrolling.
Example: Page Load
window.addEventListener("load", () => {
console.log("Page fully loaded!");
});Example: Window Resize
window.addEventListener("resize", () => {
console.log("Window resized to:", window.innerWidth, "x", window.innerHeight);
});Example: Scroll Event
window.addEventListener("scroll", () => {
console.log("You scrolled!");
});๐ Common Event Types Reference
๐ฑ๏ธ Mouse Events
- click โ Element clicked
- dblclick โ Double-clicked
- mouseenter โ Mouse enters element
- mouseleave โ Mouse leaves
- mousemove โ Mouse moves
โจ๏ธ Keyboard Events
- keydown โ Key pressed
- keyup โ Key released
- keypress โ Deprecated
๐งพ Form Events
- submit โ Form submitted
- input โ While typing
- change โ Value changed
- focus โ Element focused
- blur โ Element loses focus
๐ Window Events
- load โ Page loaded
- resize โ Window resized
- scroll โ Page scrolled
๐ฏ Practice Challenge
Create event handlers for the following:
1๏ธโฃ A click event that logs a message
button.addEventListener("click", () => {
console.log("Button clicked!");
});2๏ธโฃ A keyboard event that detects specific keys
document.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
console.log("You pressed Enter!");
}
});3๏ธโฃ A form submission that prevents default behavior
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log("Form submission prevented!");
});4๏ธโฃ Use the event object to log event properties
element.addEventListener("click", (event) => {
console.log("Target:", event.target);
console.log("Type:", event.type);
});- โข Create a counter that increments on button click
- โข Build a color picker that changes background on key press
- โข Make a form with real-time validation as users type
- โข Create a scroll progress indicator
๐ฌ Recap
- โ Events make web pages interactive and dynamic
- โ addEventListener() is the modern way to handle all event types
- โ The event object provides detailed information
- โ Use preventDefault() to stop browser defaults
- โ Combine multiple events to create smooth user experiences
Every interactive feature โ from pressing Play on YouTube to typing in a search bar โ starts with a JavaScript event.
Mastering events turns you from a coder into a true frontend developer!
End of Lesson: JavaScript Events
๐ Quick Reference โ JavaScript Events
| Event | When It Fires |
|---|---|
| click | User clicks element |
| keydown | Key is pressed |
| submit | Form is submitted |
| input | User types into field |
| addEventListener | el.addEventListener('click', fn) |
Lesson Complete โ JavaScript Events!
You can now make web pages respond to user interactions โ clicks, typing, scrolling, and form submissions!
Practice quiz
What is the modern, recommended way to handle an event?
- element.onclick = fn
- element.attachEvent(fn)
- element.addEventListener(type, fn)
- element.handle(fn)
Answer: element.addEventListener(type, fn). addEventListener is the modern, reliable way and lets you attach multiple listeners without overwriting.
When does the 'click' event fire?
- When the user clicks the element
- When a key is pressed
- When a form is submitted
- When the page loads
Answer: When the user clicks the element. The click event fires when the user clicks the element โ used for buttons, links, and cards.
What does event.preventDefault() do?
- Stops the event from firing
- Removes the listener
- Logs the event
- Stops the browser's default action, like a form reload
Answer: Stops the browser's default action, like a form reload. preventDefault stops default behaviour such as a form submitting/reloading or a link navigating.
Which property tells you which key was pressed in a keydown handler?
- event.code only
- event.key
- event.value
- event.pressed
Answer: event.key. event.key gives the value of the key the user pressed.
How many listeners can you attach to one element with addEventListener?
- As many as you want โ they do not overwrite each other
- Only one
- Up to three
- One per event type, replacing the previous
Answer: As many as you want โ they do not overwrite each other. addEventListener lets you attach as many listeners as you like; they all run and none overwrite the others.
Which form event fires while the user is typing in a field?
- submit
- blur
- input
- load
Answer: input. The input event fires on every keystroke in real time as the value changes.
Which property of the event object is the element that triggered it?
- event.element
- event.target
- event.source
- event.node
Answer: event.target. event.target references the element that triggered the event; event.type gives the event's name.
Which event fires when an input loses focus?
- focus
- input
- change
- blur
Answer: blur. blur fires when an element loses focus; focus fires when it gains focus.
Which keyboard event is deprecated, with keydown recommended instead?
- keyup
- keypress
- keydown
- keyhold
Answer: keypress. keypress is deprecated; the lesson recommends using keydown instead.
On the window object, which event signals the page has fully loaded?
- ready
- open
- load
- start
Answer: load. window's 'load' event fires when the page is fully loaded.
Continue this course
- Previous: DOM Manipulation
- Next: Arrays and Objects โ Store lists and structured data, and loop through them efficiently
- Quick reference: JavaScript cheat sheet โบ DOM
- From the blog: Understanding the DOM in JavaScript ยท Understanding JavaScript Closures ยท How to Learn to Code Fast (Without Burning Out)