Lesson 5 • Beginner
JavaScript Events ⚡
Learn how to make your web pages come alive by responding to user interactions like clicks, key presses, and form submissions.
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
.htmlfile 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
HTML:
<button id="clickMe">Click Me!</button>
JavaScript:
const button = document.getElementById("clickMe");
button.addEventListener("click", () => {
console.log("Button clicked!");
});🟢 Output in Console:
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:
HTML:
<button id="mouseBtn">Hover or Click</button>
JavaScript:
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!"));🟢 Console Output Example:
Mouse entered! Clicked! Mouse left!
mouseenter and mouseleave are great for adding hover animations or tooltips.⌨️ 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);
});🟢 Console Output:
Key pressed: a Key released: a
event.key property tells you exactly which key was pressed — useful for hotkeys or text inputs.🧾 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
HTML:
<form id="userForm"> <input type="text" placeholder="Enter name" id="nameInput" /> <button type="submit">Submit</button> </form>
JavaScript:
const form = document.getElementById("userForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevents form refresh
console.log("Form submitted!");
});🟢 Output:
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);
});🟢 Output:
Value changed: Brayan
Every 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.
Example:
document.addEventListener("click", (event) => {
console.log("Clicked element:", event.target);
console.log("Event type:", event.type);
});🟢 Output Example:
Clicked element: <button id="mouseBtn">Hover or Click</button> Event type: click
Example: Stopping Default Behavior
Some elements (like links or forms) have default behaviors.
You can stop those actions using event.preventDefault().
HTML:
<a href="https://google.com" id="link">Go to Google</a>
JavaScript:
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.
HTML:
<h2>Press any key!</h2> <p id="displayKey">Waiting for input...</p>
JavaScript:
const displayKey = document.getElementById("displayKey");
document.addEventListener("keydown", (event) => {
displayKey.textContent = `You pressed: ${event.key}`;
});🟢 Output (on the page):
You pressed: a
🧩 Example — Change Background on Click
HTML:
<button id="colorBtn">Change Background</button>
JavaScript:
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 clickeddblclick— Double-clickedmouseenter— Mouse enters elementmouseleave— Mouse leavesmousemove— Mouse moves
⌨️ Keyboard Events
keydown— Key pressedkeyup— Key releasedkeypress— Deprecated
🧾 Form Events
submit— Form submittedinput— While typingchange— Value changedfocus— Element focusedblur— Element loses focus
🌍 Window Events
load— Page loadedresize— Window resizedscroll— Page scrolled
JavaScript Events Practice
Practice event handling with simulated events!
// ========================================
// EVENT HANDLING PRACTICE
// ========================================
console.log("⚡ JavaScript Events Demo\n");
// 1. Click Event Simulation
console.log("=== Click Event ===");
let clickCount = 0;
function handleClick() {
clickCount++;
console.log(`Button clicked ${clickCount} time(s)!`);
}
// Simulate 3 clicks
handleClick();
handleClick();
handleClick();
// 2. Keyboard Event Simulation
console.log("\n=== Keyboard Event ===");
function h
...🎯 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);
});💡 Bonus Challenges:
- • 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
💡 Pro Tip
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 5 — JavaScript Events
Next up: Learn how to work with Arrays & Objects to manage data! 📦
📋 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 5 Complete — JavaScript Events!
You can now make web pages respond to user interactions — clicks, typing, scrolling, and form submissions!
Up next: Arrays & Objects — the two most important data structures in JavaScript! 📦
Sign up for free to track which lessons you've completed and get learning reminders.