completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Events in Lit

Learn Lit events with live examples: @event listeners, this, passive and once options, window listeners, and dispatching events that cross shadow roots.

By the end, you can
  • 01
    Listen the Lit wayUse @event in a template, know why a new arrow function adds no new listener, and why this is the component.
  • 02
    Put each listener in the right placeSet passive, once, and capture, listen on the host or the shadow root, and clean up listeners on document and window.
  • 03
    Send events the page can useDispatch a bubbling, composed event after updateComplete, only for what the user did, and read event.target across shadow roots.

How do events work in Lit?

Leaf and Kettle's online menu has an Add button on every tea. Ravi presses Add Sencha. The menu item counts the cup. But the cart at the top of the page should count it too. The item's button lives in the item's shadow root, out of the page's reach.

How does a Lit component hear the click? And how does it tell the rest of the page?

In Lit, you listen with @ in the template, like @click=${this.add}. Lit adds the listener and calls your method with this set to the component. To tell the page, the component dispatches its own event, with bubbles and composed set, so the event can leave its shadow root.

Here is a menu item that does both:

A menu item that hears a click and tells the pagePop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module">  import "./tea-menu-item.js";  document.addEventListener("tea-added", (event) => {    console.log(`The page heard: one more ${event.target.name}`);  });</script>
ResultLoading…
  • Lines 1 to 3 are the import map from lesson 20.1. The name lit means Lit 3.3.3, from esm.sh.
  • Line 4 puts one menu item on the page. Line 6 loads the tea-menu-item.js tab.
  • Lines 7 to 9 listen on the whole document for an event called tea-added. They print the name of the item that sent it.

The tea-menu-item.js tab holds the component:

tea-menu-item.js: one listener in, one event outJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number } };

  constructor() {
    super();
    this.cups = 0;
  }

  add() {
    this.cups += 1;
    this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
  }

  render() {
    return html`<button @click=${this.add}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 4 declares two reactive properties, name and cups (lesson 20.2).
  • Line 17 is the listener: @click followed by the method to call.
  • Line 12 counts one more cup. Line 13 sends a new event, tea-added, from the item itself.
  • Line 18 shows the count.

Click Add Sencha twice. The item shows In cart: 2. The console prints The page heard: one more Sencha twice.

Real-life analogyA waiter between the table and the kitchen

At Leaf and Kettle, a customer waves to the waiter. The waiter writes it on the pad. Then he calls the order to the kitchen. The kitchen never sees the table. It only hears the call.

In real life: A customer waving to the waiter
In JavaScript: A click on the item's button
In real life: The waiter noting it on the pad
In JavaScript: add() raising cups
In real life: Calling "one more Sencha!" to the kitchen
In JavaScript: this.dispatchEvent(new Event("tea-added", …))
In real life: The kitchen, which never sees the table
In JavaScript: The page's listener on document
The main idea

A Lit component listens with @event=${listener} in its template. Lit adds the listener for you, and this in it is the component. The component speaks with this.dispatchEvent(), and an event with bubbles and composed reaches the page.

Earlier lessons covered events in depth. Lesson 5.3 dispatched them, and lesson 9.1 showed how they change at a shadow root. This lesson is about what Lit adds, and the habits that make Lit components good at events.

What does @click do in a Lit template?

Lesson 20.3 met the @ binding. Lit's docs say it is like calling addEventListener() on the element (Lit). But what does Lit really add? This page counts it.

Counting the click listeners Lit addsPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script>  const added = [];  const addEventListener = EventTarget.prototype.addEventListener;  EventTarget.prototype.addEventListener = function (type, listener, options) {    if (type === "click") added.push(listener);    return addEventListener.call(this, type, listener, options);  };</script><script type="module">  import "./tea-menu-item.js";  const item = document.querySelector("tea-menu-item");  await item.updateComplete;  for (let n = 1; n <= 3; n++) {    item.shadowRoot.querySelector("button").click();    await item.updateComplete;  }  console.log(`In cart: ${item.cups}. Click listeners added: ${added.length}`);  console.log(`What Lit added has a handleEvent() method: ${typeof added[0].handleEvent === "function"}`);</script>
ResultLoading…
  • Lines 5 to 12 wrap addEventListener(). Every click listener added after it goes into the list added. A plain script runs before any module, so it catches Lit's first one too.
  • Line 16 waits for the first draw. Lines 17 to 20 click the button three times. Each click draws the item again.
  • Lines 21 and 22 print what the list holds.
tea-menu-item.js: a new arrow function on every drawJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number } };

  constructor() {
    super();
    this.cups = 0;
  }

  render() {
    return html`<button @click=${() => (this.cups += 1)}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);

Line 12 is the only change from the overview. The listener is an arrow function written in the template. So every draw makes a new one.

It prints In cart: 3. Click listeners added: 1 and What Lit added has a handleEvent() method: true.

Four draws made four arrow functions. Yet the button got one listener, and it isn't any of them. For each binding, Lit keeps a small object called a part (lesson 20.3). For @, it's an EventPart, and the part itself is the listener. Here is the heart of it:

EventPart adds itself as the listener, shortened from lit-html.tsJavaScript
if (shouldRemoveListener) {
  this.element.removeEventListener(this.name, this, oldListener);
}
if (shouldAddListener) {
  this.element.addEventListener(this.name, this, newListener);
}
this._$committedValue = newListener;

handleEvent(event) {
  if (typeof this._$committedValue === "function") {
    this._$committedValue.call(this.options?.host ?? this.element, event);
  } else {
    this._$committedValue.handleEvent(event);
  }
}

This is lit-html.ts, lines 2095 to 2118, at lit 3.3.3, without its types. In plain words, line by line:

  1. Lines 4 and 5 add the listener. The second argument is this: the part, not your function.
  2. Line 7 keeps the newest value you gave. It runs on every draw, but lines 1 and 4 almost never do.
  3. Lines 9 to 15 run when the event comes. handleEvent() calls the function kept on line 7.

Line 1 runs only when you give nothing, or change capture, once, or passive. Line 4 runs when there's no listener yet, or right after line 1 (lines 2069 to 2082). The comment above the class says why: it saves calls to addEventListener() "if the listener changes frequently, such as when an inline function is used as a listener" (lines 2020 to 2030).

A card, button, labeled the element. An arrow goes to a card, Lit's part, labeled added once, as the listener. On the right, three crossed-out function cards: draw 1, draw 2, and draw 3, each an arrow function. Below them, a function card, draw 4, with an arrow from the part, labeled called on each click.<button>the elementLit's partadded once, as the listenerdraw 1: () => …draw 2: () => …draw 3: () => …draw 4: () => …called on each click
Lit adds its part to the button once. Each draw gives the part a new arrow function, and the part forgets the old one. So the page prints Click listeners added: 1 after four draws.
Real-life analogyOne phone line, a new note beside it

Leaf and Kettle has one phone line. Beside it is a note that says who answers today. Each morning, Asha writes a new note. Nobody puts in a new phone line for that.

In real life: The shop's one phone line
In JavaScript: Lit's part, the one listener on the button
In real life: The note saying who answers today
In JavaScript: The function from the newest draw
In real life: A fresh note each morning
In JavaScript: A new arrow function on each draw
In real life: Putting in a new line
In JavaScript: Taking the listener off and adding it again

Why it matters: an arrow function in a template costs one small function per draw, and no new listener. Write the one that reads best.

Removing a listener

To take a listener off, give nothing, null, or undefined (Lit). Here a sold-out tea stops listening:

A menu item that stops listening when sold outPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><button id="sold-out">Mark Sencha sold out</button><script type="module">  import "./tea-menu-item.js";  const item = document.querySelector("tea-menu-item");  document.querySelector("#sold-out").onclick = () => (item.soldOut = true);</script>
ResultLoading…
tea-menu-item.js: nothing in place of the listenerJavaScript
import { LitElement, html, nothing } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number }, soldOut: { type: Boolean } };

  constructor() {
    super();
    this.cups = 0;
    this.soldOut = false;
  }

  add() {
    this.cups += 1;
  }

  render() {
    return html`<button @click=${this.soldOut ? nothing : this.add}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 17 of the tab picks the listener. While the tea is in stock, it's this.add. Once it's sold out, it's nothing, from line 1.
  • Line 9 of the page sets the property when you click Mark Sencha sold out.

Click Add Sencha twice: In cart: 2. Click Mark Sencha sold out, then Add Sencha again. It stays at In cart: 2. Lit called removeEventListener() with its part, so the button is deaf now.

What is this in a Lit event listener?

Line 17 of the overview passed this.add with no bind(). Yet this.cups worked. Line 11 of the excerpt says why: Lit calls your function with this.options?.host, or the element when there's no host. This page tries both, with Lit's plain render():

The same function, rendered with and without a hostPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="plain"></div><div id="hosted"></div><script type="module">  import { html, render } from "lit";  const cart = { owner: "Asha" };  function who() {    console.log(this === cart ? "this is Asha's cart" : `this is <${this.localName}>`);  }  render(html`<button @click=${who}>Plain render</button>`, document.querySelector("#plain"));  render(html`<button @click=${who}>With a host</button>`, document.querySelector("#hosted"), { host: cart });</script>
ResultLoading…
  • Line 7 takes html and render from Lit. There's no component on this page.
  • Line 8 makes a plain object, Asha's cart. Lines 9 to 11 print what this is.
  • Line 12 renders a button with no options. Line 13 renders one with the cart as its host.

Click Plain render. It prints this is <button>. Click With a host. It prints this is Asha's cart.

A LitElement always renders its template with { host: this } (lit-element.ts, line 137, used on line 171). So in a component, this is the component in every function listener of its template. Lit's docs call these listeners bound to the component (Lit). Lesson 20.3 compared it to a doorbell that always rings in the shop that fitted it.

Three things follow:

  • @click=${this.add} is enough. @click=${() => this.add()} works too, but the arrow adds nothing.
  • A listener object is different. Lit calls its own handleEvent() (line 13 of the excerpt), so this is the object. Use an arrow function inside it, as the next section does.
  • A listener you add yourself with addEventListener() never goes through Lit. The browser calls it with this set to the element it's on (MDN). For those, use an arrow function (arrow functions and this).

How do you make a Lit listener passive, once, or capture?

addEventListener() takes options as its third argument (once, passive and signal):

  • once: true runs the listener one time, then takes it off.
  • capture: true runs it on the event's way down, before the target hears it (capture and bubble).
  • passive: true promises the listener won't call preventDefault(). The browser can then scroll at once, without waiting for it (MDN).

An @ binding has no third argument. Lit gives you two other ways. In TypeScript, use the @eventOptions decorator, one of Lit's built-in decorators (Lit):

tea-pour.ts: a passive listener with @eventOptionsTypeScript
import { LitElement, html } from "lit";
import { customElement, eventOptions } from "lit/decorators.js";

@customElement("tea-pour")
export class TeaPour extends LitElement {
  @eventOptions({ passive: true })
  heard(event: Event) {
    event.preventDefault();
    console.log(`The tray heard it. defaultPrevented: ${event.defaultPrevented}`);
  }

  render() {
    return html`<div @click=${this.heard}>
      <button>Pour</button>
    </div>`;
  }
}
  • Line 2 takes eventOptions from lit/decorators.js.
  • Line 6 marks heard() as passive. Line 13 uses it as usual.

The decorator copies the options onto the method itself: event-options.ts, line 76 is Object.assign(method, options). Then line 5 of the excerpt passes your value as the third argument, the options. So the browser reads passive from the method. Decorators need a compiler such as TypeScript or Babel (lesson 20.2).

In plain JavaScript, give an object with a handleEvent() method and the options (Lit). Try each one here:

Playground: once, capture, and passive on a Lit listener
A tray that listens around a Pour buttonPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-pour></tea-pour><script type="module">  import { LitElement, html } from "lit";  class TeaPour extends LitElement {    heard(event) {      event.preventDefault();      console.log(`The tray heard it. defaultPrevented: ${event.defaultPrevented}`);    }    render() {      const listener = this.heard;      return html`<div @click=${listener}>        <button @click=${() => console.log("The button heard it")}>Pour</button>      </div>`;    }  }  customElements.define("tea-pour", TeaPour);</script>
ResultLoading…
Try it yourself
A plain method hears every click, after the button

Click Pour twice. Each click prints The button heard it, then The tray heard it. defaultPrevented: true. The click bubbles up from the button to the tray.

Only line 13 changes. Pick each choice, click Pour twice, and read the console.
  • Lines 8 to 11 are the tray's listener. It calls preventDefault() and prints whether that worked.
  • Line 13 is your choice. Line 14 puts it on the tray, a div. Line 15 gives the button its own listener.
  • A method: each click prints The button heard it, then The tray heard it. defaultPrevented: true. The click bubbles up from the button.
  • once: true: the second click prints only The button heard it.
  • capture: true: the tray speaks first, on the click's way down to the button.
  • passive: true: it prints defaultPrevented: false. Chrome ignored the call, and wrote a warning about it in the console.

Line 13 makes a new object on every draw. That's fine. Lit compares only capture, once, and passive (lines 2069 to 2076). If they stay the same, the listener stays. If one changes, Lit takes its listener off and adds it again. And once lasts for the element: after it has run, later draws don't put it back.

Where should a Lit component add its own listeners?

Some listeners don't fit in the template. You may want every click on the whole component, or a key pressed anywhere on the page. Lit's docs give each one a place.

On the host and on the shadow root

A menu item listening on itself and on its shadow rootPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module" src="./tea-menu-item.js"></script>
ResultLoading…
tea-menu-item.js: two listeners of its ownJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {} };

  constructor() {
    super();
    this.addEventListener("click", (event) => console.log(`Host: target is <${event.target.localName}>`));
  }

  createRenderRoot() {
    const root = super.createRenderRoot();
    root.addEventListener("click", (event) => console.log(`Shadow root: target is <${event.target.localName}>`));
    return root;
  }

  render() {
    return html`<button>Add ${this.name}</button>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Line 8 listens on the host, the component's own element, in the constructor. Lit's docs name the constructor as a good place for that (Lit).
  • Lines 11 to 15 listen on the shadow root. The root doesn't exist in the constructor yet. So the item overrides createRenderRoot(), which makes it (lesson 20.5). Line 14 must return the root.
  • Line 18 draws a button with no listener at all.

Click Add Sencha. It prints Shadow root: target is <button>, then Host: target is <tea-menu-item>.

The shadow root hears the click first, with the real button. The host hears it next, retargeted to the item itself (lesson 9.1). Neither needs removing. They sit on the component's own nodes, and go away with it (the Lit Cheat Sheet).

On document and window

A menu should close when someone presses Escape, wherever focus is. That key goes to the page, so the menu listens on document. Lit's docs say to add such a listener in connectedCallback() and remove it in disconnectedCallback() (Lit). See what happens without the removal:

Playground: a document listener with and without cleanup
A menu that leaves the page and comes backPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module">  import "./tea-menu.js";  const menu = document.querySelector("tea-menu");  const pressEscape = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));  pressEscape();  menu.remove();  pressEscape();  document.body.append(menu);  pressEscape();</script>
ResultLoading…
Try it yourself
The menu still answers after it leaves the page

It prints Escape heard. On the page: true, then Escape heard. On the page: false, then true again. The removed menu kept answering, because the document still held its listener.

Only the tea-menu.js tab changes: the second choice adds lines 13 to 16. Pick each choice and read the console.
tea-menu.js: listen while on the pageJavaScript
import { LitElement, html } from "lit";

export class TeaMenu extends LitElement {
  #onKey = (event) => {
    if (event.key === "Escape") console.log(`Escape heard. On the page: ${this.isConnected}`);
  };

  connectedCallback() {
    super.connectedCallback();
    document.addEventListener("keydown", this.#onKey);
  }

  disconnectedCallback() {
    document.removeEventListener("keydown", this.#onKey);
    super.disconnectedCallback();
  }

  render() {
    return html`<p>The tea menu is open.</p>`;
  }
}

customElements.define("tea-menu", TeaMenu);
  • Lines 4 to 6 are the listener, a private arrow function field. As an arrow, it keeps this as the menu. As a field, it's one function, so the same one can be removed later.
  • Lines 8 to 11 add it whenever the menu joins the page.
  • Lines 13 to 16 remove it whenever the menu leaves. The first choice doesn't have them.
  • On the page, line 8 makes a helper that sends Escape to the document. Line 9 presses it, line 10 removes the menu, line 11 presses again, and lines 12 and 13 put the menu back and press once more.

Without the cleanup, it prints Escape heard. On the page: true, then Escape heard. On the page: false, then true again. With it, it prints Escape heard. On the page: true twice.

Two halves. Left, no disconnectedCallback(): a card, document, with an arrow down to a function card, #onKey, and an arrow down to a card, tea-menu, off the page. Label: On the page: false. Right, with disconnectedCallback(): the same document card, a crossed-out #onKey card labeled removed when it left, and the tea-menu, off the page card with no arrows. Label: nothing prints.no disconnectedCallback()document#onKeytea-menu, off the pageOn the page: falsewith disconnectedCallback()document#onKeyremoved when it lefttea-menu, off the pagenothing prints
The document holds on to every listener added to it. Without the removal, the menu that left the page still runs on each Escape. With it, nothing ties the menu to the page any more.
Real-life analogyA newspaper delivered to an empty house

Ravi gets the morning paper delivered. When he moves out, he cancels it. If he forgets, the paper keeps coming to the empty house. The shop still has his name on its list.

In real life: Signing up for the morning paper
In JavaScript: document.addEventListener() in connectedCallback()
In real life: Moving out
In JavaScript: The menu leaving the page
In real life: Cancelling the paper
In JavaScript: removeEventListener() in disconnectedCallback()
In real life: Papers piling up at the empty house
In JavaScript: Escape heard. On the page: false

The document keeps every listener added to it. While it keeps the menu's, the menu can't be freed from memory either. Why add it in connectedCallback(), not the constructor? An element can leave the page and come back, and connectedCallback() runs each time (lesson 3.3). So the listener comes back with it.

Here is every place side by side. Read each row across:

Where a Lit component can listen
Where you listenA click on the item's button arrives with targetDo you remove it?
@click on the button, in the templateThe button.No. Lit adds it, and takes it off when you give nothing.
@click on a list around the buttonsThe button. It's in the same shadow root.No. Lit looks after it, as above.
this.addEventListener() in the constructorThe component. The browser hides the button.No. It goes away with the component.
The shadow root, in createRenderRoot()The button.No. It goes away with the component.
document or window, in connectedCallback()The component, like any page code.Yes, in disconnectedCallback().

How do you handle events from a list in Lit?

A list of teas can give each row its own listener. Or one listener on the list can hear them all, because clicks bubble. That's event delegation (event delegation):

One listener for a whole list of teasPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-list></tea-list><script type="module" src="./tea-list.js"></script>
ResultLoading…
tea-list.js: @click on the list, not on each rowJavaScript
import { LitElement, html } from "lit";

export class TeaList extends LitElement {
  static properties = { teas: { attribute: false } };

  constructor() {
    super();
    this.teas = ["Sencha", "Assam", "Oolong"];
  }

  pick(event) {
    const button = event.target.closest("button");
    if (button) console.log(`Picked ${button.dataset.tea}`);
  }

  render() {
    return html`<ul @click=${this.pick}>
      ${this.teas.map((tea) => html`<li><button data-tea=${tea}>${tea}</button></li>`)}
    </ul>`;
  }
}

customElements.define("tea-list", TeaList);
  • Line 17 puts one @click on the ul. Line 18 draws the rows with map() (lesson 20.4), each button with a data-tea attribute.
  • Line 12 finds the button. event.target is the real button here, because the list and the rows share one shadow root. closest() still finds it if the click lands on something inside the button.
  • Line 13 reads which tea it was.

Click Assam. It prints Picked Assam.

With 100 teas, a listener on each row means 100 listeners. On the list, it's one. Lit's docs say adding listeners is very fast, and usually no problem (Lit). So for a short list, @click=${() => this.add(tea)} on each row is fine, and easier to read. Delegation only works for events that bubble. focus doesn't, so listen for focusin, or on each row.

How do you dispatch an event from a Lit component?

Call this.dispatchEvent() with a new event, as line 13 of the overview did. Two options decide who hears it: bubbles and composed. In Lit apps, a component often sits inside another component's shadow root. Here a menu item sits inside a cart:

Playground: who hears an event from a menu item inside a cart
A page with a cart, and a menu item inside the cartPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module">  import "./tea-cart.js";  document.addEventListener("tea-added", () => console.log("The page heard it"));</script>
ResultLoading…
Try it yourself
bubbles and composed: every level hears it

Click Add Sencha. It prints The cart's list heard it, The cart heard it, then The page heard it. The event bubbled up and left both shadow roots.

Only line 7 of the tea-menu-item.js tab changes. Pick each choice, click Add Sencha, and read the console.
tea-cart.js: a cart that listens in two placesJavaScript
import { LitElement, html } from "lit";
import "./tea-menu-item.js";

export class TeaCart extends LitElement {
  constructor() {
    super();
    this.addEventListener("tea-added", () => console.log("The cart heard it"));
  }

  render() {
    return html`<div @tea-added=${() => console.log("The cart's list heard it")}>
      <tea-menu-item name="Sencha"></tea-menu-item>
    </div>`;
  }
}

customElements.define("tea-cart", TeaCart);
tea-menu-item.js: the event and its optionsJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {} };

  add() {
    const event = new Event("tea-added", { bubbles: true, composed: true });
    this.dispatchEvent(event);
  }

  render() {
    return html`<button @click=${this.add}>Add ${this.name}</button>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • In tea-cart.js, line 7 listens on the cart itself. Line 11 listens on the div around the item. @ works for any event name, built in or your own.
  • Line 12 puts the item inside the cart's shadow root.
  • In tea-menu-item.js, line 7 makes the event with your choice of options. Line 8 sends it from the item.
  • On the page, line 7 listens on the document.
  • bubbles and composed: The cart's list heard it, The cart heard it, The page heard it.
  • bubbles only: just The cart's list heard it. It stops at the edge of the cart's shadow root.
  • composed only: just The cart heard it. A composed event that doesn't bubble still reaches the host of each root it leaves (Lit).
  • neither: nothing at all.

For an event the page should hear, set both, as Lit's docs do (Lit). If only the parent component needs it, bubbles alone keeps it private (lesson 9.2). A listener can also answer back: on a cancelable event, its preventDefault() makes dispatchEvent() return false (lesson 5.3). Lit's context works the same way, with events sent up the tree (lesson 19.4).

What does event.target show outside a Lit component?

Each listener in the playground heard the same event. Did they all see the same target? This cart reports it at every level:

What each listener sees as the targetPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module">  import "./tea-cart.js";  document.addEventListener("tea-added", (event) => {    console.log(`The page: target <${event.target.localName}>, path starts at <${event.composedPath()[0].localName}>`);  });</script>
ResultLoading…
tea-cart.js: report the target and the pathJavaScript
import { LitElement, html } from "lit";
import "./tea-menu-item.js";

const report = (where, event) =>
  console.log(`${where}: target <${event.target.localName}>, path starts at <${event.composedPath()[0].localName}>`);

export class TeaCart extends LitElement {
  constructor() {
    super();
    this.addEventListener("tea-added", (event) => report("The cart", event));
  }

  render() {
    return html`<div @tea-added=${(event) => report("The cart's list", event)}>
      <tea-menu-item name="Sencha"></tea-menu-item>
    </div>`;
  }
}

customElements.define("tea-cart", TeaCart);
  • Lines 4 and 5 make report(). It prints the event's target and the first node of its path.
  • Line 10 reports from the cart itself. Line 14 reports from the list inside its shadow root.
  • Lines 7 to 9 of the page print the same, from the document.

Click Add Sencha. It prints The cart's list: target <tea-menu-item>, path starts at <tea-menu-item>, then The cart: target <tea-cart>, path starts at <tea-menu-item>, then The page: target <tea-cart>, path starts at <tea-menu-item>.

Three rows, one for each listener, in the order they hear tea-added. Columns: who hears it, sees target, and path starts at. Row one: the cart's list, tea-menu-item, tea-menu-item. An arrow goes down, labeled leaves the cart's shadow root. Row two: the cart, tea-cart, tea-menu-item. An arrow goes down. Row three: the page, tea-cart, tea-menu-item.who hears itsees targetpath starts atthe cart's listtea-menu-itemtea-menu-itemleaves the cart's shadow rootthe carttea-carttea-menu-itemthe pagetea-carttea-menu-itemthe same event, seen from three places
Inside the cart's shadow root, the target is the item. From the cart's edge outward, it is the cart. The first node in composedPath() is the item at every level.
Real-life analogyBooth 4 wants one more cup

A family sits in booth 4. Someone calls out "one more cup!" The waiter across the room hears "booth 4 wants a cup". He can't tell which person spoke. Someone at the same table can.

In real life: The person who called out
In JavaScript: The menu item, first in composedPath()
In real life: The booth
In JavaScript: The cart's shadow root
In real life: "Booth 4 wants a cup"
In JavaScript: event.target is the cart, outside it
In real life: Someone at the same table
In JavaScript: The cart's list, which sees the item

That's retargeting. Outside a shadow root, the browser shows the host as the target, so outside code never sees what's inside (lesson 9.1). Every event that leaves a Lit component seems to come from the component (Lit). event.composedPath() lists every node on the trip, so its first one is where the event started (MDN). Lit's docs keep it for rare cases, because it shows a component's insides.

Why it matters: to know which item spoke, listen inside the cart's own shadow root, as line 14 does. There, the target is the item. Exercise 1 asks what the page sees for the click itself.

Why dispatch after updateComplete in Lit?

Lit doesn't draw the moment a property changes. It draws a little later, in a microtask: a small job the browser runs as soon as your code ends (lesson 20.2). So what does a listener see if the item sends its event at once? This page reads the item's screen from the listener:

Playground: send the event right away, or after the update
A page that reads what the item showsPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module">  import "./tea-menu-item.js";  document.addEventListener("tea-added", (event) => {    const shown = event.target.shadowRoot.querySelector("span").textContent;    console.log(`cups is ${event.target.cups}. The item shows: ${shown}`);  });</script>
ResultLoading…
Try it yourself
Right away: the page reads the old screen

Click Add Sencha. It prints cups is 1. The item shows: In cart: 0. The property changed, but Lit hadn't drawn it yet.

Only the tea-menu-item.js tab changes: the second choice makes add() async and adds line 13. Pick each choice, click Add Sencha, and read the console.
tea-menu-item.js: wait for the update, then sendJavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number } };

  constructor() {
    super();
    this.cups = 0;
  }

  async add() {
    this.cups += 1;
    await this.updateComplete;
    this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
  }

  render() {
    return html`<button @click=${this.add}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • On the page, line 8 reads the text the item shows. Line 9 prints it next to the property.
  • In the tab, line 11 makes add() async. Line 13 waits for updateComplete, a promise that settles once Lit has drawn the change. Line 14 sends the event after that.

Right away, it prints cups is 1. The item shows: In cart: 0. After updateComplete, it prints cups is 1. The item shows: In cart: 1.

Two rows. Top, right away: cards click, cups = 1, dispatch, then In cart: 0, labeled sees the old count. Bottom, after await this.updateComplete: cards click, cups = 1, Lit draws, dispatch, then In cart: 1, labeled sees the new count.right awayclickcups = 1dispatchIn cart: 0sees the old countafter await this.updateCompleteclickcups = 1Lit drawsdispatchIn cart: 1sees the new count
Lit draws after your click listener ends. Send the event right away, and the listener reads In cart: 0. Wait for updateComplete first, and it reads In cart: 1.
Real-life analogyCalling the order when the cup is on the counter

Asha calls "order ready!" only when the cup is on the counter. If she called first, Ravi would walk up and find nothing there.

In real life: Pouring the tea
In JavaScript: Lit drawing the change
In real life: Calling "order ready!"
In JavaScript: this.dispatchEvent()
In real life: Waiting until the cup is out
In JavaScript: await this.updateComplete
In real life: A customer finding an empty counter
In JavaScript: The listener reading In cart: 0

Lit's docs say the same: when an event tells about a change on screen, await updateComplete first (Lit). Lesson 21.1 follows the whole update, step by step.

When should a Lit component not dispatch an event?

The page may set a property itself, like restoring a saved cart. Should the item announce that? Compare two places for the same event:

Playground: send the event from the click, or from updated()
A page that sets cups itselfPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script>  document.addEventListener("tea-added", (event) => console.log(`tea-added, cups: ${event.target.cups}`));</script><script type="module">  import "./tea-menu-item.js";  const item = document.querySelector("tea-menu-item");  await item.updateComplete;  item.cups = 3;</script>
ResultLoading…
Try it yourself
From the click: only the shopper's action sends it

Nothing prints when the page loads, though line 12 sets cups to 3. Click Add Sencha, and it prints tea-added, cups: 4.

Only the tea-menu-item.js tab changes: the second choice moves the event into updated(), lines 15 to 17. Pick each choice, read the console, then click Add Sencha.
tea-menu-item.js: an event sent from updated()JavaScript
import { LitElement, html } from "lit";

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number } };

  constructor() {
    super();
    this.cups = 0;
  }

  add() {
    this.cups += 1;
  }

  updated(changed) {
    if (changed.has("cups")) this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
  }

  render() {
    return html`<button @click=${this.add}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Lines 5 to 7 of the page listen before anything loads. Line 12 sets cups to 3, as the page's own change.
  • Lines 15 to 17 of the tab send the event whenever cups changed, whoever changed it.

From the click, nothing prints until you click. Then it prints tea-added, cups: 4. From updated(), it prints tea-added, cups: 0 and tea-added, cups: 3 before any click.

Lit's docs give the rule. Send events for what the user did, or for changes the component finds out later. Don't send them when the owner set a property or an attribute (Lit). The browser works this way: setting input.value fires no input and no change event. A thermostat that rang a bell each time you turned it would only tell you what you just did.

Why it matters: the page already knows about its own change. And a listener that sets the property back could start a loop.

Should a Lit component use CustomEvent or an Event subclass?

So far the listener read event.target. Often it wants data too: which tea? There are two ways to carry it. Lit's docs show both and call either one reasonable (Lit). Lesson 5.3 compared them. Justin Fagnani prefers a class (Stop Using CustomEvent):

  • The data sits right on the event, like a click's clientX, not in a detail bag.
  • The class is the one place that sets the name and the options, so every copy of the event matches.
  • In TypeScript, the class is the event's type.
A menu item that sends its own event classPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Assam"></tea-menu-item><script type="module">  import { TeaAddedEvent } from "./tea-menu-item.js";  document.addEventListener(TeaAddedEvent.type, (event) => {    console.log(`One more ${event.tea}. A TeaAddedEvent: ${event instanceof TeaAddedEvent}`);  });</script>
ResultLoading…
tea-menu-item.js: TeaAddedEvent extends EventJavaScript
import { LitElement, html } from "lit";

export class TeaAddedEvent extends Event {
  static type = "tea-added";

  constructor(tea) {
    super(TeaAddedEvent.type, { bubbles: true, composed: true });
    this.tea = tea;
  }
}

export class TeaMenuItem extends LitElement {
  static properties = { name: {} };

  render() {
    return html`<button @click=${() => this.dispatchEvent(new TeaAddedEvent(this.name))}>Add ${this.name}</button>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • Lines 3 to 10 of the tab are the class. Line 4 keeps the name. Line 7 passes it and the options to super(). Line 8 puts the tea on the event.
  • Line 16 sends a new one on each click.
  • On the page, line 6 imports the class. Line 7 listens by its name. Line 8 reads event.tea.

Click Add Assam. It prints One more Assam. A TeaAddedEvent: true.

The same event as a CustomEvent puts the tea in detail:

The same event as a CustomEventJavaScript
// Sending it
this.dispatchEvent(new CustomEvent("tea-added", { detail: { tea: this.name }, bubbles: true, composed: true }));

// Hearing it
cart.addEventListener("tea-added", (event) => console.log(event.detail.tea));

Line 2 puts the tea in detail, and line 5 reads it from there. In TypeScript, add a class to HTMLElementEventMap, the list of events every HTML element has:

TeaAddedEvent in HTMLElementEventMapPop out in the code editor (opens in a new tab)TypeScript
class TeaAddedEvent extends Event {  static type = "tea-added";  tea: string;   constructor(tea: string) {    super(TeaAddedEvent.type, { bubbles: true, composed: true });    this.tea = tea;  }} declare global {  interface HTMLElementEventMap {    "tea-added": TeaAddedEvent;  }} const cart = document.createElement("tea-cart");cart.addEventListener("tea-added", (event) => {  console.log(event.tea);  //                ^?});document.addEventListener("tea-added", (event) => console.log(event.tea)); export {};
  • Lines 11 to 15 add the event to the list. So on line 19, event.tea is a string.
  • Line 22 has an error on purpose. document isn't an HTML element, so its list doesn't have tea-added, and event is a plain Event. For document and window too, use GlobalEventHandlersEventMap, as lesson 5.3 did.

Building a tea cart that hears every menu item

Now the whole menu: a cart with three items. It uses every lesson of this module: reactive properties, a property binding, a list, static styles, and events.

A tea cart with three menu itemsPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module">  import "./tea-cart.js";  document.addEventListener("tea-cart-change", (event) => {    console.log(event.target.shadowRoot.querySelector("p").textContent);  });</script>
ResultLoading…
tea-cart.js: hear the items, pass the counts downJavaScript
import { LitElement, html, css } from "lit";
import "./tea-menu-item.js";

export class TeaCart extends LitElement {
  static properties = { teas: { attribute: false }, counts: { state: true } };
  static styles = css`p { font-weight: bold; }`;

  constructor() {
    super();
    this.teas = ["Sencha", "Assam", "Oolong"];
    this.counts = {};
  }

  async add(event) {
    this.counts = { ...this.counts, [event.tea]: (this.counts[event.tea] ?? 0) + 1 };
    await this.updateComplete;
    this.dispatchEvent(new Event("tea-cart-change", { bubbles: true, composed: true }));
  }

  render() {
    const total = Object.values(this.counts).reduce((sum, cups) => sum + cups, 0);
    return html`<div @tea-added=${this.add}>
        ${this.teas.map((tea) => html`<tea-menu-item name=${tea} .cups=${this.counts[tea] ?? 0}></tea-menu-item>`)}
      </div>
      <p>Cups in the cart: ${total}</p>`;
  }
}

customElements.define("tea-cart", TeaCart);
tea-menu-item.js: show the cups, ask for one moreJavaScript
import { LitElement, html, css } from "lit";

export class TeaAddedEvent extends Event {
  static type = "tea-added";

  constructor(tea) {
    super(TeaAddedEvent.type, { bubbles: true, composed: true });
    this.tea = tea;
  }
}

export class TeaMenuItem extends LitElement {
  static properties = { name: {}, cups: { type: Number } };
  static styles = css`:host { display: flex; gap: 8px; align-items: center; margin: 4px 0; }`;

  constructor() {
    super();
    this.cups = 0;
  }

  render() {
    return html`<button @click=${() => this.dispatchEvent(new TeaAddedEvent(this.name))}>Add ${this.name}</button>
      <span>In cart: ${this.cups}</span>`;
  }
}

customElements.define("tea-menu-item", TeaMenuItem);
  • In tea-cart.js, line 22 is one @tea-added on the div around the items. Inside the cart's shadow root, the target is the item that spoke.
  • Line 15 makes a new counts object, so Lit sees the change (lesson 20.2). Line 16 waits for the draw. Line 17 tells the page.
  • Line 23 passes each count down with .cups (lesson 20.3). Line 25 shows the total.
  • In tea-menu-item.js, line 22 only asks for one more cup. It never changes cups itself, and it sends nothing when the cart sets it. Line 14 is its static style (lesson 20.5).

Click Add Sencha, Add Assam, then Add Sencha. The console prints Cups in the cart: 1, Cups in the cart: 2, and Cups in the cart: 3. The items show In cart: 2, In cart: 1, and In cart: 0.

Events go up, and properties come down (lesson 18.4). The items never talk to each other. The cart sits between them and keeps the counts, the way the shelf of lesson 18.4 did for its badge and tiles.

Where does this listener go?
  • A click on the Add button the component draws
  • Typing in a search box inside the component
  • A click on any of 50 rows the component draws
  • Any click on the component, even on the children the page slots into it
  • Arrow keys pressed anywhere inside the component
  • Escape pressed anywhere on the page, to close a menu
  • The window changing size
  • A click outside the component, to close a popup
Try it yourself
0 of 8 correct

Sort each listener into the place a Lit component should add it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "A new arrow function in the template adds a new listener on every draw." No. Lit's part is the one listener. It only swaps the function it calls. Four draws printed Click listeners added: 1.
  • "@click needs bind(this) or an arrow function, or this is lost." No. A LitElement renders with { host: this }, and Lit calls every listener function with that host.
  • "@eventOptions works in any JavaScript file." No. It's a decorator, so it needs TypeScript or Babel. In plain JavaScript, use an object with handleEvent() and the options.
  • "A listener on document can go in the constructor and stay there." No. Add it in connectedCallback() and remove it in disconnectedCallback(), or the removed menu keeps answering.
  • "Outside the component, event.target is the button that was clicked." No. Outside a shadow root, the target is the host. Only composedPath() shows where the event started.
  • "bubbles: true is enough for the page to hear it." No. Without composed, the event stops at the edge of the shadow root it started in.
  • "You can rename an event after you make it, with event.type." No. type is read-only. Setting it in a class that extends Event throws a TypeError. Pass the name to super().
  • "A component should announce every change to its properties." No. Announce what the user did. When the page sets a property, the page already knows.

Practice exercises

Exercise 1 · Warm-upPredict what the page sees for a click

The cart in the tea-cart.js tab draws the overview's menu item. Read the page without running it. What does the console print when you click Add Sencha?

<script type="importmap">
  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<tea-cart></tea-cart>
<script type="module">
  import "./tea-cart.js";
  document.addEventListener("click", (event) => {
    console.log(`${event.target.localName} ${event.composedPath()[0].localName}`);
  });
</script>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCount the listeners on three teapots

    The page draws three teapot buttons five times. Read it without running it. What does the console print?

    <script type="importmap">
      { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
    </script>
    <tea-teapots></tea-teapots>
    <script>
      const added = [];
      const addEventListener = EventTarget.prototype.addEventListener;
      EventTarget.prototype.addEventListener = function (type, listener, options) {
        if (type === "click") added.push(listener);
        return addEventListener.call(this, type, listener, options);
      };
    </script>
    <script type="module">
      import "./tea-teapots.js";
      const pots = document.querySelector("tea-teapots");
      for (let n = 1; n <= 5; n++) {
        pots.pours = n;
        await pots.updateComplete;
      }
      console.log(`Click listeners added: ${added.length}`);
    </script>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeLet the page hear the menu item

      Click Add Sencha. The cups go up, but the page prints nothing. Fix the item so the page hears it.

      <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module">  import "./tea-cart.js";  document.addEventListener("tea-added", (event) => {    console.log(`The page heard tea-added from <${event.target.localName}>`);  });</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeStop the menu answering after it leaves

        This menu has a disconnectedCallback(), yet it prints four lines, one with On the page: false. Fix the tea-menu.js tab.

        <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module">  import "./tea-menu.js";  const menu = document.querySelector("tea-menu");  const pressEscape = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));  pressEscape();  menu.remove();  pressEscape();  document.body.append(menu);  pressEscape();</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeSend one event from a whole list

          Clicking a tea does nothing. Make every button in the list send tea-added, with one listener for the whole list.

          <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-list></tea-list><script type="module">  import "./tea-list.js";  document.addEventListener("tea-added", (event) => console.log(`One more ${event.tea}`));</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeKeep the rating quiet when the page sets it

            The rating prints two lines before anyone clicks. Only a click should send change. Fix the tea-cup-rating.js tab.

            <script type="importmap">  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating></tea-cup-rating><script>  document.addEventListener("change", (event) => console.log(`change: ${event.target.value} cups`));</script><script type="module">  import "./tea-cup-rating.js";  const rating = document.querySelector("tea-cup-rating");  await rating.updateComplete;  rating.value = 3;</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The Events in Lit quiz · 8 questionsScore: first tries count
              1. Question 1 of 8This page has a menu item and a listener on the document. You click Add Sencha once. What does the console print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <tea-menu-item name="Sencha"></tea-menu-item>
                <script type="module">
                  import "./tea-menu-item.js";
                  document.addEventListener("tea-added", (event) => {
                    console.log(`The page heard: one more ${event.target.name}`);
                  });
                </script>

                Choose an answer to see the explanation.

              2. Question 2 of 8A template has @click=${() => (this.cups += 1)}, so every draw makes a new function. The page draws it four times. How many times did Lit call addEventListener()?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <script type="importmap">
                  { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
                </script>
                <tea-menu-item name="Sencha"></tea-menu-item>
                <script>
                  const added = [];
                  const addEventListener = EventTarget.prototype.addEventListener;
                  EventTarget.prototype.addEventListener = function (type, listener, options) {
                    if (type === "click") added.push(listener);
                    return addEventListener.call(this, type, listener, options);
                  };
                </script>
                <script type="module">
                  import "./tea-menu-item.js";
                  const item = document.querySelector("tea-menu-item");
                  await item.updateComplete;
                  for (let n = 1; n <= 3; n++) {
                    item.shadowRoot.querySelector("button").click();
                    await item.updateComplete;
                  }
                  console.log(`In cart: ${item.cups}. Click listeners added: ${added.length}`);
                  console.log(`What Lit added has a handleEvent() method: ${typeof added[0].handleEvent === "function"}`);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 8Inside a LitElement, why is this the component in a method used as @click=${this.add}?

                Choose an answer to see the explanation.

              4. Question 4 of 8In a plain JavaScript file with no decorators, how do you make a Lit listener passive?

                Choose an answer to see the explanation.

              5. Question 5 of 8A menu item inside a cart's shadow root dispatches new Event("tea-added", { composed: true }), with no bubbles. Who hears it?

                Choose an answer to see the explanation.

              6. Question 6 of 8A Lit menu closes when someone presses Escape anywhere on the page. Where should its keydown listener go?

                Choose an answer to see the explanation.

              7. Question 7 of 8Why does add() write await this.updateComplete before this.dispatchEvent(...)?

                Choose an answer to see the explanation.

              8. Question 8 of 8The page restores a saved cart with item.cups = 3. Should the item dispatch tea-added?

                Choose an answer to see the explanation.

              Key takeaways

              • Listen with @event=${listener} in the template. The value is a function or an object with handleEvent().
              • Lit adds one part per binding as the listener. A new function on each draw adds no new listener.
              • Give nothing, null, or undefined to take the listener off.
              • this in a listener function is the component, because LitElement renders with { host: this }.
              • Set once, capture, and passive with an object in JavaScript, or with @eventOptions in TypeScript.
              • Listen on the host in the constructor, on the shadow root in createRenderRoot(), and on document or window only in connectedCallback(), removed in disconnectedCallback().
              • Dispatch with bubbles and composed so the page hears it. Outside, event.target is your component.
              • Await updateComplete before an event about the screen, and send events for what the user did.

              That ends module 20. A Lit component declares its properties (20.2), draws them with a template (20.3), shows parts and lists (20.4), and styles itself with one shared sheet (20.5). Now it talks to the page, too.

              Remember the one-liner.
              Listen with @ in the template, and speak with an event that bubbles and is composed, once the screen shows the change.

              Sources

              The facts on this page come from these docs, posts, and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: The Lit update lifecycle, the next lesson of the Lit stage. It follows one update from a property change to the drawn screen.

              CompleteFrontend Clear concepts. Working examples.