JavaScript · Lesson 22 / 32 · English
JavaScript Events
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
An event listener connects a user action to code. Register the handler once, keep state separately, and update the visible page when the event occurs.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Events in JavaScript
Events are things that happen in the browser — a user clicks a button, moves the mouse, presses a key, or the page finishes loading. JavaScript lets you react to these events.
Adding Event Listeners
const btn = document.querySelector("#myBtn");
// Preferred way: addEventListener
btn.addEventListener("click", function(event) {
console.log("Clicked!", event);
});
// Arrow function
btn.addEventListener("click", (e) => {
console.log(e.target); // the element clicked
console.log(e.type); // "click"
console.log(e.clientX, e.clientY); // mouse position
});
// Remove listener (must reference same function)
const handler = () => console.log("clicked");
btn.addEventListener("click", handler);
btn.removeEventListener("click", handler);Common Event Types
| Category | Event | When it fires |
|---|---|---|
| Mouse | click | Element clicked |
| Mouse | mouseover / mouseout | Mouse enters/leaves element |
| Mouse | mousemove | Mouse moves over element |
| Keyboard | keydown / keyup | Key is pressed/released |
| Keyboard | keypress | Character key pressed (deprecated) |
| Form | submit | Form is submitted |
| Form | input / change | Input value changes |
| Form | focus / blur | Element gains/loses focus |
| Window | load | Page fully loaded |
| Window | DOMContentLoaded | HTML parsed (before images) |
| Window | resize / scroll | Window resized/scrolled |
Event Delegation
// Instead of attaching to each item, attach to parent
const list = document.querySelector("#todo-list");
list.addEventListener("click", (e) => {
// Check if the clicked element is a list item
if (e.target.matches("li")) {
e.target.classList.toggle("done");
}
if (e.target.matches(".delete-btn")) {
e.target.closest("li").remove();
}
});
// Prevent default behaviour
document.querySelector("a").addEventListener("click", (e) => {
e.preventDefault(); // stop navigation
});
// Stop event bubbling
btn.addEventListener("click", (e) => {
e.stopPropagation(); // don't bubble up to parent
});A complete example
This is a complete HTML document. Use the HTML preview editor below, not the Node console. Press Run to refresh the rendered page.
<!doctype html>
<html lang="en"><meta charset="utf-8"><title>Events practice</title>
<body><button id="complete">Complete a lesson</button><p id="count">Completed: 0</p>
<script>
let completed = 0;
document.querySelector("#complete").addEventListener("click", () => {
completed += 1;
document.querySelector("#count").textContent = "Completed: " + completed;
});
</script></body></html>Predict first. Reveal the expected result.
Initially: Completed: 0 After two button clicks: Completed: 2
Make one change. See what happens.
For this browser example, interact with the rendered preview after pressing Run.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Add a Reset button that returns the count to 0.
Reveal the answer and reasoning
Register a click listener on the Reset button. Set completed = 0 and update #count with the same rendering rule.
One mistake to avoid: Pass a function to addEventListener. Writing handler() calls it immediately instead of registering it for a later event.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.