Classic JS Tutorial | JS in VS 2026 | JS Examples | jQuery
⚡ Lesson 12 of 30

Events & Event Listeners

Respond to user interactions — clicks, keyboard input, forms, and custom events.

addEventListener

const btn = document.querySelector("#myBtn");

btn.addEventListener("click", function(event) {
  console.log("Clicked!", event.target);
});

// Arrow function shorthand
btn.addEventListener("click", e => alert("Hello!"));

Mouse Events

const box = document.querySelector(".box");

box.addEventListener("mouseover", () => box.style.background = "#f7c948");
box.addEventListener("mouseout",  () => box.style.background = "");
box.addEventListener("dblclick",  () => console.log("Double click!"));

Keyboard Events

document.addEventListener("keydown", e => {
  console.log(`Key: ${e.key}, Code: ${e.code}`);
  if (e.key === "Enter") console.log("Enter pressed!");
  if (e.ctrlKey && e.key === "s") {
    e.preventDefault(); // stop browser save dialog
    console.log("Ctrl+S intercepted");
  }
});

Form Events

const form = document.querySelector("form");
const input = document.querySelector("#username");

input.addEventListener("input", e => {
  console.log("Typing:", e.target.value);
});

form.addEventListener("submit", e => {
  e.preventDefault(); // stop page reload
  console.log("Submitted:", input.value);
});

Event Delegation

Attach one listener to a parent instead of many listeners to children — more efficient:

document.querySelector("#list").addEventListener("click", e => {
  if (e.target.tagName === "LI") {
    e.target.classList.toggle("done");
    console.log("Toggled:", e.target.textContent);
  }
});
← Lesson 11🏠 HomeLesson 13 →