DOM events

These programs are page scripts: they run in a browser, and the lines under each one are what its console prints. Each program dispatches its own event, so the output is the same on every run; a real click does the same thing with real coordinates.

addEventListener

addEventListener attaches a reaction to an element without touching its markup. The callback receives an event object, and TypeScript picks the right event type from the event name, so a click handler sees a PointerEvent, a kind of MouseEvent, with its coordinates. The program dispatches one click at 10, 20 and prints the two coordinates. The page holds one button:

<button>add</button>

const btn = document.querySelector<HTMLButtonElement>("button"); if (btn === null) { throw new Error("missing button"); } btn.addEventListener("click", (event) => { console.log(event.clientX, event.clientY); }); btn.dispatchEvent(new MouseEvent("click", { clientX: 10, clientY: 20 }));

10 20

The event parameter needs no annotation: the click name tells the compiler its exact type. clientX and clientY are therefore checked, not guessed.

Typed event targets

Using btn from the previous section, narrow the event target before touching it. The target arrives as a wide type, and instanceof shrinks it to the concrete element, unlocking typed fields like disabled with no casts at all. The page holds one button:

<button>add</button>

const btn = document.querySelector<HTMLButtonElement>("button"); if (btn === null) { throw new Error("missing button"); } btn.addEventListener("click", (event) => { const target = event.target; if (target instanceof HTMLButtonElement) { target.disabled = true; } }); btn.dispatchEvent(new MouseEvent("click", { bubbles: true })); console.log(btn.disabled);

true

The check does the work that a cast would fake. Inside the if, target is a button with every button field available. The program dispatches one click and prints the disabled flag of the button.

Delegate lists

One listener on the parent handles every child. Clicks bubble up, so read the actual clicked item from the event target and match it with closest. Rows added later work at once, with no extra listeners. The page holds a list of two rows:

<ul><li>milk</li><li>bread</li></ul>

const list = document.querySelector<HTMLUListElement>("ul"); if (list === null) { throw new Error("missing ul"); } list.addEventListener("click", (event) => { const target = event.target; if (!(target instanceof HTMLElement)) { return; } const item = target.closest("li"); if (item !== null) { item.classList.toggle("done"); } }); const second = list.querySelectorAll("li")[1]; second.dispatchEvent(new MouseEvent("click", { bubbles: true })); console.log(second.className);

done

closest walks from the clicked node up to the nearest li, or returns null outside any row. The toggle then flips the done class exactly where the user clicked. The program clicks the second row and prints its class list.

Once and cleanup

Listeners pile up when added twice, so remove what is no longer needed. Pass once for handlers that must fire a single time. For manual control, keep the function reference and call removeEventListener later with the same reference. The page holds one button:

<button>add</button>

const btn = document.querySelector<HTMLButtonElement>("button"); if (btn === null) { throw new Error("missing button"); } function welcome(): void { console.log("welcome"); } btn.addEventListener("click", welcome, { once: true }); btn.dispatchEvent(new MouseEvent("click")); btn.dispatchEvent(new MouseEvent("click"));

welcome

once removes the listener after the first click automatically. Anonymous arrows cannot be removed by reference, which is one more reason to name handlers like welcome. The program clicks twice and the listener runs once.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What type does the event parameter of a click listener have?

    Answer

    PointerEvent, because the event name picks the type

    The overload of addEventListener for the click name gives the callback the precise event type, and PointerEvent extends MouseEvent.

  2. What does the once option of addEventListener do?

    Answer

    It removes the listener after its first call

    The browser removes the handler itself after the first event, so a second click does nothing.

  3. Why put one listener on the list instead of one per row?

    Answer

    Because clicks bubble to the list, so rows added later need no new listener

    Delegation reads the clicked row from the event target, so rows added after the listener was attached work at once.

  4. What does target.closest("li") do in a click handler?

    Answer

    It walks up from the clicked node to the nearest li, or gives null

    It walks towards the root, which is how a click on a link inside a row still finds the row.

  5. Why does a handler have to be a named function to be removable?

    Answer

    removeEventListener needs the same function reference it was given

    Removal compares the reference, and a fresh arrow is a different function every time.

  6. What does this program print? const bus = new EventTarget(); bus.addEventListener("ping", () => { console.log("pong"); }); bus.dispatchEvent(new Event("ping"));

    Answer

    pong

    The dispatch runs the listener registered for the ping event, and the listener prints pong.

  7. What does this program print? const bus = new EventTarget(); bus.addEventListener("ping", () => { console.log("first"); }); bus.addEventListener("ping", () => { console.log("second"); }); bus.dispatchEvent(new Event("ping"));

    Answer

    first / second

    Listeners for one event run in the order they were added.

  8. What does the compiler say about this program? const btn = document.querySelector<HTMLButtonElement>("button")!; btn.addEventListener("click", (event) => { console.log(event.key); });

    Answer

    error TS2339: Property 'key' does not exist on type 'PointerEvent'.

    A click event has coordinates but no key, and the compiler knows the difference from the event name.

  9. What does the compiler say about this program? const btn = document.querySelector<HTMLButtonElement>("button")!; btn.addEventListener("keydown", (event) => { console.log(event.clientX); });

    Answer

    error TS2339: Property 'clientX' does not exist on type 'KeyboardEvent'.

    A keyboard event has no coordinates, so the field of another event type is refused at compile time.

  10. What does event.target hold when a click lands on a link inside a row?

    Answer

    The element that was actually clicked, often the link

    The target is the clicked node, which is why a delegated handler walks up with closest to find the row.

Article author: Arthur Isaev