JavaScript – DOM & Building Real Projects
intermediate30 XP

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

JavaScript
const button = document.querySelector("#myButton");

button.addEventListener("click", function() {
  console.log("Button was clicked! 🖱️");
});

Or with an arrow function (cleaner):

JavaScript
button.addEventListener("click", () => {
  console.log("Clicked! 🎯");
});

Common Event Types

EventWhen it fires
clickUser clicks the element
mouseoverMouse moves onto element
mouseoutMouse moves off element
keydownAny key is pressed
keyupAny key is released
inputText input changes
submitForm is submitted
loadPage finishes loading

🌟 Click Counter

HTML
<button id="counter-btn">Click me! 0</button>
JavaScript
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

JavaScript
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)

HTML
<input id="search" placeholder="Search games...">
<div id="results"></div>
JavaScript
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

JavaScript
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

01/3
Which method is used to listen for events on an element?