Events – Reacting to Clicks, Keys & More!
Make your webpage respond to user actions — button clicks, key presses, mouse movements and form submissions!
Events — Your Webpage Listens and Responds! 👂
An event is anything a user does on your page — clicking, typing, hovering, scrolling. JavaScript can listen for these and respond instantly!
addEventListener — The Professional Way
const button = document.querySelector("#myButton");
button.addEventListener("click", function() {
console.log("Button was clicked! 🖱️");
});Or with an arrow function (cleaner):
button.addEventListener("click", () => {
console.log("Clicked! 🎯");
});Common Event Types
| Event | When it fires |
|-------|--------------|
| click | User clicks the element |
| mouseover | Mouse moves onto element |
| mouseout | Mouse moves off element |
| keydown | Any key is pressed |
| keyup | Any key is released |
| input | Text input changes |
| submit | Form is submitted |
| load | Page finishes loading |
🌟 Click Counter
<button id="counter-btn">Click me! 0</button>let clicks = 0;
const btn = document.getElementById("counter-btn");
btn.addEventListener("click", () => {
clicks++;
btn.textContent = "Click me! " + clicks;
if (clicks === 10) {
btn.textContent = "🎉 10 clicks! You win!";
btn.style.backgroundColor = "gold";
}
});Keyboard Events
document.addEventListener("keydown", (event) => {
console.log("Key pressed: " + event.key);
if (event.key === "ArrowUp") {
console.log("Moving up! ⬆️");
}
if (event.key === " ") {
console.log("Spacebar pressed! Jump! 🦘");
}
});This is how browser games work! Every game listens for keydown events.
Input Events (Live Typing)
<input id="search" placeholder="Search games...">
<div id="results"></div>const games = ["Minecraft", "Roblox", "Fortnite", "Among Us", "Terraria"];
const search = document.getElementById("search");
const results = document.getElementById("results");
search.addEventListener("input", () => {
const query = search.value.toLowerCase();
const matches = games.filter(game =>
game.toLowerCase().includes(query)
);
results.innerHTML = matches.map(g => `<p>🎮 ${g}</p>`).join("");
});This is exactly how search boxes work on YouTube and Google! 🔍
Form Submit Event
const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stops page from refreshing!
const name = document.querySelector("#name").value;
console.log("Form submitted by: " + name);
});Always use event.preventDefault() to stop forms from refreshing the page!
Quick check
Which method is used to listen for events on an element?