JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 12: Events and InteractionLesson 57 of 150About 40 minutes

Lesson 57: Event objects

01Opening question

A listener knows that a click happened. How does it find out where, on what, and with which keys held down?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Every listener receives an event object describing what happened. preventDefault stops the browser's own action, here following the link.

const link = document.querySelector("#docs");
link.addEventListener("click", (event) => {
  event.preventDefault();
  console.log(event.type, event.target.id, event.defaultPrevented);
});
link.click();

03Objective and prerequisites

Learning objective: Read the event object (type, target, currentTarget, key, modifier keys) and stop default browser behaviour with preventDefault.

You need: Lesson 56: Event listeners

Skills practised: Events, Event objects.

04Explanation

The browser passes an event object as the first argument to every listener. Name it event (or e) and read its properties.

event.type is the event name, event.target is the element where the event started, and event.key tells you which key was pressed.

event.shiftKey, event.ctrlKey, event.altKey and event.metaKey are true while those keys are held, so you can build shortcuts such as Ctrl+S.

event.preventDefault() cancels the browser's normal action: following a link, submitting a form, or typing a character.

05Definitions

Event object
The object passed to a listener describing the event: its type, target and details.
event.target
The element where the event started, such as the exact element that was clicked.
event.currentTarget
The element whose listener is currently running.
preventDefault
A method that cancels the browser's default action for the event.
Modifier key
Shift, Ctrl, Alt or Meta, reported by shiftKey, ctrlKey, altKey and metaKey.

Open the full glossary

06Visual learning object

Event listener laboratory. Trigger clicks and key presses on a live preview and read the properties of each event object.

Loading the interactive object…

Open the full Event listener laboratory page with its guided experiment.

07Examples

ex-057-01target and currentTarget Browser page (sandboxed preview)

Clicking a child inside the listening element makes the two differ.

const card = document.querySelector("#card");
card.addEventListener("click", (event) => {
  console.log("target:", event.target.tagName, "current:", event.currentTarget.id);
});
document.querySelector("#buy").click();
card.click();
Sample input
None
Expected output
target: BUTTON current: card target: DIV current: card
Common mistake
Using event.target when you meant the element that has the listener.
Try this
Click the h3 from code and predict the output.
Source
examples/ex-057-01-target-vs-current.js

ex-057-02A Ctrl+S shortcut Browser page (sandboxed preview)

Modifier flags combine with event.key to make shortcuts.

const notes = document.querySelector("#notes");
notes.addEventListener("keydown", (event) => {
  if (event.ctrlKey && event.key === "s") {
    event.preventDefault();
    console.log("Saved:", notes.value);
  }
});
const press = (init) => notes.dispatchEvent(new KeyboardEvent("keydown", { cancelable: true, ...init }));
press({ key: "s" });
press({ key: "s", ctrlKey: true });
Sample input
None
Expected output
Saved: Draft
Common mistake
Forgetting preventDefault, so the browser's own Save dialog opens too.
Try this
Also accept metaKey for Mac users.
Source
examples/ex-057-02-shortcut.js

ex-057-03Cancelling a link Browser page (sandboxed preview)

preventDefault keeps the page where it is and lets JavaScript decide.

const link = document.querySelector("#delete");
link.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("Ask before deleting", link.getAttribute("href"));
});
const ev = new MouseEvent("click", { cancelable: true });
const notCancelled = link.dispatchEvent(ev);
console.log(notCancelled, ev.defaultPrevented);
Sample input
None
Expected output
Ask before deleting /delete?id=7 false true
Common mistake
Returning false from an addEventListener handler and expecting it to cancel the action; only preventDefault does.
Try this
Only cancel when a checkbox named confirm is unchecked.
Source
examples/ex-057-03-prevent-link.js

ex-057-04Reading event details Browser page (sandboxed preview)

A single handler can serve several event types by checking event.type.

const input = document.querySelector("#name");
const log = (event) => console.log(event.type, event.target.value);
for (const type of ["focus", "input", "blur"]) input.addEventListener(type, log);
input.dispatchEvent(new FocusEvent("focus"));
input.value = "Ada L";
input.dispatchEvent(new Event("input"));
input.dispatchEvent(new FocusEvent("blur"));
Sample input
None
Expected output
focus Ada input Ada L blur Ada L
Common mistake
Writing three nearly identical handlers instead of one that reads event.type.
Try this
Count how many input events happen.
Source
examples/ex-057-04-event-log.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Which button was clicked?

Use currentTarget instead of a shared variable.

const buttons = document.querySelectorAll(".size");
let chosen = "";
for (const button of buttons) {
  button.addEventListener("click", () => {
    chosen = buttons[0].dataset.size;
  });
}
buttons[2].click();
console.log("Size:", chosen);

Move with the arrow keys

Branch on event.key.

let x = 0;
document.addEventListener("keydown", (event) => {
  // TODO: ArrowRight adds 1, ArrowLeft subtracts 1, other keys do nothing
  document.querySelector("#pos").textContent = x;
});
for (const key of ["ArrowRight", "ArrowRight", "a", "ArrowLeft", "ArrowRight"]) {
  document.dispatchEvent(new KeyboardEvent("keydown", { key }));
}
console.log("x =", x);

Confirm external links

Cancel a default action conditionally.

// Write guard(link): it adds a click listener that cancels the click
// (preventDefault) only for links with a data-external attribute,
// and logs "Blocked: <href>" when it does.

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <ul id="list"><li id="a">A</li></ul>
const list = document.getElementById("list");
list.addEventListener("click", (e) => {
  console.log(e.target.id, e.currentTarget.id);
});
document.getElementById("a").click();

What is printed?

10Debugging investigation

Clicking the icon deletes nothing

Clicking the trash icon inside the Delete button should delete item 42, but it logs "Deleting undefined". Clicking the button's text works.

let deleted = null;
const button = document.querySelector(".delete");
button.addEventListener("click", (event) => {
  deleted = event.target.dataset.id;
  console.log("Deleting " + deleted);
});
document.querySelector(".icon").click();

More cases in the Debugging Detective Laboratory

11Practical scenario

Keyboard-friendly editors

A code editor in the browser cancels Tab's default focus change and inserts spaces instead, and uses Ctrl or Cmd plus S to save without opening the browser's own dialog. Both read the event object and call preventDefault only for those keys.

const handled = (e) => e.key === "Tab" || ((e.ctrlKey || e.metaKey) && e.key === "s");
console.log(handled({ key: "Tab" }), handled({ key: "s", metaKey: true }), handled({ key: "s" }));

12Knowledge check

1. What is event.target?

  • The element whose listener is running
  • The element where the event started
  • The document
  • The previous element

2. A listener on a ul logs event.currentTarget.tagName. An li inside it is clicked. What is printed?

  • LI
  • UL
  • BODY
  • undefined

3. What does event.preventDefault() do?

  • Stops other listeners
  • Cancels the browser's default action
  • Removes the listener
  • Stops the event from bubbling

4. Why does this shortcut never fire for Ctrl+S?

if (e.ctrlKey && e.key === "S") save();
  • The key name is "s", not "S", when Shift is not held
  • ctrlKey does not exist
  • keydown has no key
  • The handler must return true

5. Which property tells you whether Shift is held?

  • event.shift
  • event.shiftKey
  • event.modifiers
  • event.key === "Shift" always

6. Three buttons share one handler. Which way of reading the clicked button's data-id is most reliable?

  • A loop variable captured with var
  • event.currentTarget.dataset.id
  • document.querySelector("button").dataset.id
  • this inside an arrow function

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Which button was clicked?: Prints Size: L; Medium works too
  • Move with the arrow keys: Prints x = 2; The page shows 2
  • Confirm external links: Prints the blocked link; Internal links are not cancelled

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-12-events-and-interaction/lesson-057-event-objects/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • Listeners receive an event object.
  • target is where the event started; currentTarget is where the listener is.
  • key and the modifier flags describe keyboard input.
  • preventDefault cancels the browser's default action.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation event objects
Context: I am learning event objects in JavaScript.
Task: Explain event.target, event.currentTarget, event.key and preventDefault with small HTML examples.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction event objects drill
Context: I have practised event objects.
Task: Give me six event-object puzzles about target and currentTarget and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging event objects bug
Context: My shared click handler always reads the first button instead of the one that was clicked.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation event objects practice
Context: I finished the event objects exercises.
Task: Create three exercises that use event.key, modifier keys and preventDefault.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review event objects review
Context: Here is my code that uses event objects.
Task: Review my event handlers for confusion between target and currentTarget.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.