JavaScript Events

</>Coding Tamilan.← JavaScript course

JavaScript · Lesson 22 / 32 · English

JavaScript Events

Understand the idea. Change the code. Build confidence with one focused experiment.

Detailed notesBrowser previewPractice + answer

Read this lesson in தமிழ் ↗.

01 / Understand

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.

02 / Explore

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

JavaScript reference fragmentCODE
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

CategoryEventWhen it fires
MouseclickElement clicked
Mousemouseover / mouseoutMouse enters/leaves element
MousemousemoveMouse moves over element
Keyboardkeydown / keyupKey is pressed/released
KeyboardkeypressCharacter key pressed (deprecated)
FormsubmitForm is submitted
Forminput / changeInput value changes
Formfocus / blurElement gains/loses focus
WindowloadPage fully loaded
WindowDOMContentLoadedHTML parsed (before images)
Windowresize / scrollWindow resized/scrolled

Event Delegation

JavaScript reference fragmentCODE
// 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
});
03 / Read & predict

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.

index.html · complete exampleCODE
<!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
04 / Experiment

Make one change. See what happens.

For this browser example, interact with the rendered preview after pressing Run.

Open editor ↗

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.

05 / Your turn

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.
Coding Tamilan · Learn by doing.