Day 11 — Events
Lesson
Topic 1 Part 1
const btn = document.querySelector("#my-btn");
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 2 Part 2
btn.addEventListener("click", () => {
console.log("Button clicked!");
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 3 You can attach multiple listeners — all run
// You can attach multiple listeners — all run
btn.addEventListener("click", () => {
console.log("Second handler also fires");
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 4 Part 4
const btn = document.querySelector("#my-btn");
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 5 Part 5
btn.addEventListener("click", (e) => {
console.log(e.type); // "click"
console.log(e.target); // the <button> element
console.log(e.target.textContent); // its text
console.log(e.clientX, e.clientY); // mouse coordinates
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 6 Input — e.target.value is what the user typed
// Input — e.target.value is what the user typed
const input = document.querySelector("#name-input");
input.addEventListener("input", (e) => {
console.log("User typed:", e.target.value);
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 7 Keyboard — e.key is which key
// Keyboard — e.key is which key
document.addEventListener("keydown", (e) => {
console.log("Pressed:", e.key); // "a", "Enter", "ArrowUp"
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 8 Part 8
const box = document.querySelector("#box");
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 9 Part 9
box.addEventListener("click", () => console.log("click"));
box.addEventListener("dblclick", () => console.log("double click"));
box.addEventListener("mouseover", () => box.classList.add("hover"));
box.addEventListener("mouseout", () => box.classList.remove("hover"));
box.addEventListener("contextmenu", (e) => {
e.preventDefault();
console.log("right-clicked at", e.clientX, e.clientY);
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.
Section 10 Part 10
document.querySelectorAll("#todo-list li").forEach(li => {
li.addEventListener("click", () => {
li.classList.toggle("done");
});
});
Code below mirrors ../js/lesson.js. Open DevTools → Console to see output when the script runs.