Skip to lesson content
Web Technologies › Level 17
LEVEL 17 · EVENTS

JavaScript Events and Forms

Trace browser interactions and build a clear, correctable form workflow.

⚡ Events🧭 Propagation✅ Forms + validation🧪 Labs + MCQs
01

Learning Objectives

Events

Connect meaningful native controls to their actions.

Propagation

Trace capture, target and bubble listeners.

Validation

Combine native constraints with stated task rules.

Form data

Inspect successful controls and handle submit once.

02

Events — A Signal That Something Happened

A workshop interaction
Native control

A learner activates a button or submits the form.

Event object

The browser exposes type, targets and state.

Listener

Code reads values, validates and updates feedback.

03

addEventListener — Pass the Function

function showDetails(event) {
  console.log(event.type);
}
button.addEventListener("click", showDetails);
// Later, when this listener is no longer needed:
button.removeEventListener("click", showDetails);
04

Event Object — target and currentTarget

link.addEventListener("click", event => {
  const observed = {
    type: event.type,
    target: event.target.id,
    listener: event.currentTarget.id,
    phase: event.eventPhase
  };
  console.log(observed);
});

The event-path lab records these values synchronously rather than storing the event object and later assuming currentTarget still names the listener.

05

Capture, Target and Bubble

outer.addEventListener("click", observe, { capture: true });
inner.addEventListener("click", observe, { capture: true });
link.addEventListener("click", observe);
inner.addEventListener("click", observe);
outer.addEventListener("click", observe);
Observed nested click path
Capture

Outer region → inner region.

Link listener

Read target and currentTarget separately.

Bubble

Inner region → outer region unless stopped.

06

preventDefault and stopPropagation

link.addEventListener("click", event => {
  event.preventDefault(); // cancel navigation if cancelable
  // Ancestor bubble listeners can still run.
});
07

Delegation — Listen on a Stable Parent

list.addEventListener("click", event => {
  const button = event.target.closest("button[data-action]");
  if (!button || !list.contains(button)) return;
  if (button.dataset.action === "details") {
    showWorkshopDetails(button.dataset.id);
  }
});
08

Click, Keyboard and Native Semantics

<button type="button" id="details">Show details</button>
<a href="#workshop-summary">Read workshop summary</a>
09

input, change and Editing Feedback

nameInput.addEventListener("input", () => {
  nameInput.setCustomValidity("");
  nameError.textContent = "";
  nameInput.removeAttribute("aria-invalid");
});
10

Forms — Names, Labels and Button Types

<form id="request">
  <label for="places">Places requested</label>
  <input id="places" name="places" type="number"
         min="1" max="4" step="1" required>
  <button type="submit">Preview request</button>
  <button type="button">Clear messages</button>
</form>
11

Handle submit on the Form

form.addEventListener("submit", event => {
  event.preventDefault();
  // Validate fields and display a local preview.
});
12

Native Validity and Custom Task Rules

placesInput.setCustomValidity("");
if (requested > available) {
  placesInput.setCustomValidity("Request no more than the available places.");
}
const valid = form.checkValidity();
13

FormData — Inspect Successful Controls

const data = new FormData(form);
const entries = Array.from(data.entries());
const places = Number(data.get("places"));
console.log(entries, places);
14

requestSubmit, submit and reset

form.requestSubmit(); // validation/submit workflow
// form.submit() has different behavior and bypasses that handler.

form.reset();
field.setCustomValidity("");
error.textContent = "";
15

Errors, Focus and Honest Outcomes

A useful rejection
Field text

Describe the specific correction.

Focus

Move to the first invalid control.

Status

Report a concise overall result.

Retry

Keep values and validate the corrected attempt.

16

Premium Visualizer — Form Event Journey

Follow the fixed submission path through activation, cancellation, validation, collection and reporting. Use the familiar timeline and playback controls. The lab below exposes actual event listeners and a separate form workflow.

EVENTS AND FORM TRACE
Step 1 of 5
STEP 01

Activate the native submit control

The form workflow reaches its submit listener in the local novalidate demo.

form.addEventListener("submit", handler)

What is happening?

A native form workflow is broader than one button click. This lab deliberately uses inline validation.

17

Premium Interactive — Event Path and Form Lab

Event path playground

Outer region

Local navigation marker for the event experiment.

Activate the link to inspect its event path.

[]

Local workshop-request preview

Use fictional values. HTML has 3 places available; JavaScript has 2. Each request must contain 1–4 whole places and fit the selected availability.

The form becomes available when its local handler is ready.

Submission outcome

No accepted preview yet.
18

Debugging — Identify the Event and the Workflow

Handler

Check event type, function identity and duplicate setup.

Path

Inspect target, currentTarget, phase and stopping point.

Validity

Clear stale custom errors and inspect native flags.

Data

Check names, checkbox state, strings and omitted controls.

19

Interview Questions — Flip to Explain

QUESTION

Why handle a form’s submit event rather than only its button click?

Click or press Enter to explain
ANSWER

Submit represents the form workflow, including supported implicit submission and requestSubmit. A click-only handler can miss other submission paths.

QUESTION

How do target and currentTarget differ?

Click or press Enter to explain
ANSWER

Target identifies the exposed event target; currentTarget identifies the object whose listener is currently running.

QUESTION

Does preventDefault stop bubbling?

Click or press Enter to explain
ANSWER

No. It cancels an applicable default action; propagation continues unless separately stopped.

QUESTION

Does stopPropagation cancel a link’s navigation?

Click or press Enter to explain
ANSWER

No. It stops further propagation, but default cancellation requires preventDefault when the event is cancelable.

QUESTION

What makes delegation useful for dynamic cards?

Click or press Enter to explain
ANSWER

A stable parent can observe a suitable bubbling event from descendants inserted later, while checking the intended target and scope.

QUESTION

Why clear setCustomValidity before rechecking?

Click or press Enter to explain
ANSWER

A non-empty custom message keeps a control invalid even after its visible value is corrected.

QUESTION

What does FormData do with an unchecked checkbox?

Click or press Enter to explain
ANSWER

It normally omits that control’s entry. The missing entry is not automatically the text false.

QUESTION

How do requestSubmit and submit differ?

Click or press Enter to explain
ANSWER

RequestSubmit follows the validation and submit-event workflow. The submit method bypasses constraint validation and the submit event.

20

MCQ Practice — Explain the Event and Form

PRACTICE

1. Which value should be passed to addEventListener as a callback?

PRACTICE

2. Which property identifies the object whose listener is running?

PRACTICE

3. Which observed listener runs first in the normal playground path?

PRACTICE

4. What does preventDefault do for this cancelable link click?

PRACTICE

5. What does stopPropagation do in the link listener?

PRACTICE

6. Which event should handle the request form’s workflow?

PRACTICE

7. What does novalidate change in this demo?

PRACTICE

8. Which value clears a custom validity error?

PRACTICE

9. How does FormData ordinarily represent a number input?

PRACTICE

10. What happens to the unchecked optional updates checkbox?

PRACTICE

11. Which method bypasses submit listeners and constraint validation?

PRACTICE

12. How many places can an accepted JavaScript request contain here?

21

Extra Practice — Test Specific Interactions

Normal path

Activate the nested link in normal mode. Expected: five observed listeners; target and listener IDs can differ.

Cancellation

Choose cancel navigation. Expected: five observed listeners and defaultPrevented becomes true at the link listener.

Stopping

Choose stop propagation. Expected: two capture entries plus the link entry; later inner/outer bubble entries are absent.

Blank attempt

Submit untouched fields. Expected: inline required errors and focus on the name field.

Accepted values

  • Use Demo Learner, learner@example.com, HTML, 3 places and confirmation.
  • Expected: a local accepted preview with numeric places 3.

Capacity rule

Choose JavaScript and 3 places. Expected: places error because only two are available.

Optional entry

Preview with updates unchecked, then checked. Expected: updates omitted, then updates="yes".

Correction/reset

  • Correct an invalid place count and retry, then reset.
  • Expected: stale error clears, one handling result per attempt and defaults restored.
22

Quick Revision

Listeners: Register callbacks without calling them immediately.
Targets: Separate target from current listener identity.
Path: Capture and bubble describe propagation order.
Cancel: Default action and propagation are separate decisions.
Delegation: Use a stable parent and checked descendant target.
Editing: Clear stale messages without claiming full validity.
Submit: Handle the form workflow once.
Validation: Combine native constraints and explicit task rules.
FormData: Understand strings and omitted controls.
Outcome: Preserve correction paths and report local scope honestly.
23

Glossary — Flip to Learn

TERM

Event

Click to see meaning
DEFINITION

Event

An object representing an occurrence dispatched through event targets.

TERM

Listener

Click to see meaning
DEFINITION

Listener

A callback registered to respond to an event type.

TERM

Target

Click to see meaning
DEFINITION

Target

The event target exposed to the current listener.

TERM

Current target

Click to see meaning
DEFINITION

Current target

The object whose event listener is currently running.

TERM

Capture

Click to see meaning
DEFINITION

Capture

Propagation toward the target through applicable ancestor listeners.

TERM

Bubbling

Click to see meaning
DEFINITION

Bubbling

Propagation outward through applicable ancestor listeners.

TERM

Default action

Click to see meaning
DEFINITION

Default action

A browser behavior associated with an event, such as navigation.

TERM

Delegation

Click to see meaning
DEFINITION

Delegation

Handling suitable descendant events through a parent listener.

TERM

Constraint validation

Click to see meaning
DEFINITION

Constraint validation

Checking controls against applicable native and custom validity rules.

TERM

Successful control

Click to see meaning
DEFINITION

Successful control

A form control that contributes data under the form-entry rules.

24

Final Challenge — A Clear Local Request Workflow

25

Level 17 Complete?

Before marking complete, trace a nested event, cancel its default action deliberately, submit a form through its own listener and correct a field-specific error. Completion is a local study marker rather than an assessment score.