completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

connectedCallback and disconnectedCallback

Learn when connectedCallback and disconnectedCallback run, why they can run many times, and how to clean up listeners and timers with AbortController.

By the end, you can
  • 01
    Say when each callback runsPredict what runs when an element is added, removed, moved, or hidden.
  • 02
    Write setup that can run many timesGuard one-time work, and check isConnected before work that might come too late.
  • 03
    Clean up everything the element startedStop timers and remove outside listeners with one AbortController for each time the element joins the page.

What do connectedCallback and disconnectedCallback do?

Asha's online shop for Leaf and Kettle shows a timer next to each tea that's brewing. Ravi wrote it, a tag called tea-timer. It counts the seconds since the tea went in. When Asha serves the tea, her shop takes the timer off the page.

Then she opens the console. It still says Tick: 3 s, then Tick: 4 s, once a second. The timer is gone from the page. So what is still ticking? And how can a component know that it has left the page?

connectedCallback() is a method the browser calls each time your element is put into the page. disconnectedCallback() is the method it calls each time the element is taken out. Start work in the first one. Stop it in the second one.

Both are lifecycle callbacks. You write them, and the browser calls them at set moments in the element's life. You never call them yourself. Here is a badge that prints a line from each:

A badge that says when it joins and leavesPop out in the code editor (opens in a new tab)HTML
<p>Teas: </p> <script>  class TeaBadge extends HTMLElement {    connectedCallback() {      console.log(`${this.textContent} joined the page`);    }    disconnectedCallback() {      console.log(`${this.textContent} left the page`);    }  }  customElements.define("tea-badge", TeaBadge);   const badge = document.createElement("tea-badge");  badge.textContent = "Organic";  const p = document.querySelector("p");  p.append(badge);  badge.remove();  p.append(badge);</script>
ResultLoading…
  • Lines 5 to 7 are connectedCallback(). It prints the badge's text and joined the page.
  • Lines 8 to 10 are disconnectedCallback(). It prints left the page.
  • Line 14 makes a badge by name, the way Asha's shop does. It isn't on the page yet, so nothing prints.
  • Line 17 puts the badge in the paragraph, which is on the page. The console prints Organic joined the page.
  • Line 18 takes it out again. The console prints Organic left the page.
  • Line 19 puts it back. connectedCallback() runs a second time.

The browser called each method right when a line changed the page. And it called connectedCallback() twice, once for each time the badge joined.

Three lines and three callbacks. Line 17, p.append(badge): connectedCallback runs, the badge joins. Line 18, badge.remove(): disconnectedCallback runs, the badge leaves. Line 19, p.append(badge): connectedCallback runs again, the badge joins again.line 17p.append(badge)connectedCallback()joinsline 18badge.remove()disconnectedCallback()leavesline 19p.append(badge)connectedCallback()joins again
Each time the badge joins the page, connectedCallback() runs. Each time it leaves, disconnectedCallback() runs. Line 19 runs the first one a second time.
Real-life analogyPlugging the kettle in and unplugging it

At the tea shop, the kettle moves around. Each time Ravi puts it on a counter, he plugs it in. Each time he puts it away, he unplugs it first. To move it to another counter, he unplugs it and plugs it in again. If he forgets to unplug it, it stays on in the cupboard.

In real life: Putting the kettle on a counter and plugging it in
In JavaScript: connectedCallback()
In real life: Unplugging it before you put it away
In JavaScript: disconnectedCallback()
In real life: Moving it to another counter
In JavaScript: Taking the element out and adding it somewhere else
In real life: A kettle left switched on in the cupboard
In JavaScript: A timer that keeps going after the element left
The main idea

connectedCallback() runs each time the element joins the page. disconnectedCallback() runs each time it leaves. Whatever the first one starts, the second one stops. Both can run many times for one element.

In lesson 3.2, the constructor left work for later: reading attributes and adding content. This lesson shows when "later" comes, how often it comes, and how to clean up after it.

When does connectedCallback run?

The browser calls it when the element becomes connected. That's the standard's word for "inside a document", the page the browser shows. Every element has an isConnected property. It's true when the element is in a document, and false when it isn't.

Being inside a parent isn't enough. The parent must be on the page too:

A badge in a box off the pagePop out in the code editor (opens in a new tab)HTML
<p>Teas: </p> <script src="tea-badge.js"></script> <script>  const badge = document.createElement("tea-badge");  badge.textContent = "Organic";  const box = document.createElement("div");  box.append(badge);  console.log("In a box:", badge.isConnected);  document.querySelector("p").append(box);  console.log("On the page:", badge.isConnected);</script>
ResultLoading…
  • Line 3 loads tea-badge.js, the second tab. It's the badge from the first example, in its own file.
  • Lines 6 and 7 make a badge called Organic.
  • Lines 8 and 9 make a box, a <div>, and put the badge in it. The box itself isn't on the page.
  • Line 10 prints In a box: false. The badge has a parent, but it isn't connected. No callback has run.
  • Line 11 puts the box in the paragraph. Now the badge is in the document. Its connectedCallback() prints Organic joined the page.
  • Line 12 prints On the page: true.

A badge in a box off the page is like a letter in an envelope you haven't posted. It has a home, but it isn't going anywhere yet.

So connectedCallback() runs for any change that brings the element into the document:

  • The parser reads its tag, after customElements.define() has run.
  • define() upgrades a tag that was already on the page. The constructor runs first, then connectedCallback().
  • append(), prepend(), before(), insertBefore(), or replaceWith() puts it on the page, or puts in a parent that holds it.
  • innerHTML writes its tag inside an element that's on the page.
  • It goes into a shadow root whose element is on the page. A shadow root is a private tree inside an element. MDN's page on isConnected shows this case.

Each time, the element has just joined the page, and the tag's attributes are already there. That's why lesson 3.2 moved reading them here.

Why it matters: a badge made by name, as in Asha's shop, waits quietly. Its setup runs only once it joins the page, with its attributes already set.

When does disconnectedCallback run?

It runs when a connected element stops being connected. Taking the element out is one way. Taking out something it's inside is another:

Two badges leave with their paragraph's textPop out in the code editor (opens in a new tab)HTML
<p>Teas: <tea-badge>Organic</tea-badge> <tea-badge>Fair trade</tea-badge></p> <script src="tea-badge.js"></script> <script>  const p = document.querySelector("p");  p.textContent = "Sold out";  console.log("Badges on the page:", document.querySelectorAll("tea-badge").length);</script>
ResultLoading…
  • Line 1 puts two badges in a paragraph.
  • Line 3 loads tea-badge.js. The browser upgrades both badges, and each prints joined the page.
  • Line 7 swaps everything in the paragraph for the words Sold out.
  • Both badges print left the page. Then line 8 prints Badges on the page: 0.

Line 7 never named the badges. They left as part of the paragraph's old content. The browser runs disconnectedCallback() for every custom element that leaves, however deep it sits. The same goes for innerHTML = "", replaceChildren(), and removing a parent.

It only runs for an element that was connected. Take a badge out of a box that isn't on the page, and nothing runs. It never joined, so it can't leave.

Now try it. The page has a Brewing shelf and a Ready shelf. Line 10 does one thing to the Oolong badge. Pick what it does:

Playground: which callbacks run?
Line 10 does something to the badgePop out in the code editor (opens in a new tab)HTML
<p id="brewing">Brewing: <tea-badge>Oolong</tea-badge></p><p id="ready">Ready: </p> <script src="tea-badge.js"></script> <script>  const badge = document.querySelector("tea-badge");  const brewing = document.querySelector("#brewing");  const ready = document.querySelector("#ready");  ready.append(badge);  console.log("Done");</script>
ResultLoading…
Try it yourself
disconnectedCallback() runs, then connectedCallback()

The first line is the upgrade, when line 4 loads tea-badge.js. Then line 10 moves the badge. A move takes the badge out and puts it in again, so it leaves, then joins.

Pick what line 10 does to the Oolong badge. tea-badge.js, in the second tab, prints each callback. Each choice runs in a fresh page.

Two results surprise most people. Hiding the badge runs nothing. It's still on the page, just not drawn. And append() to the shelf it's already on runs both callbacks. The next section explains why.

Why does connectedCallback run more than once?

Because an element can join the page many times. When you append() an element that's already somewhere, the browser first takes it out of its old place. Then it puts it in the new one. The DOM Standard's steps for inserting a node do it in that order. Each step runs its callback.

Frameworks move elements too. When a list is sorted, a framework may move the same elements into a new order. Nolan Lawson points out that each move is a disconnect and a reconnect for your element.

So connectedCallback() must be safe to run again. Most work is. Setting textContent, as the kit's tea-label does, gives the same result every time. Adding something is different:

An order that gets a new button on every connectPop out in the code editor (opens in a new tab)HTML
<p id="brewing">Brewing: <tea-order>Oolong</tea-order></p><p id="ready">Ready: </p> <script>  class TeaOrder extends HTMLElement {    connectedCallback() {      const button = document.createElement("button");      button.textContent = "Serve";      this.append(" ", button);    }  }  customElements.define("tea-order", TeaOrder);   const order = document.querySelector("tea-order");  document.querySelector("#ready").append(order);  console.log("Buttons:", order.querySelectorAll("button").length);</script>
ResultLoading…
  • Lines 6 to 10 add a Serve button each time the order joins the page.
  • Line 12 registers the class. The order from line 1 is upgraded, and it gets its first button.
  • Line 15 moves the order to Ready. It leaves, joins again, and gets a second button.
  • Line 16 prints Buttons: 2.

The HTML Standard warns about this. Work that must happen only once needs a guard: a check that skips it the second time.

A guard for one-time setupPop out in the code editor (opens in a new tab)HTML
<p id="brewing">Brewing: <tea-order>Oolong</tea-order></p><p id="ready">Ready: </p> <script>  class TeaOrder extends HTMLElement {    #built = false;     connectedCallback() {      if (this.#built) return;      this.#built = true;      const button = document.createElement("button");      button.textContent = "Serve";      this.append(" ", button);    }  }  customElements.define("tea-order", TeaOrder);   const order = document.querySelector("tea-order");  document.querySelector("#ready").append(order);  console.log("Buttons:", order.querySelectorAll("button").length);</script>
ResultLoading…
  • Line 6 adds #built, set to false. A name that starts with # is a private field. Only code inside the class can read it.
  • Line 9 is the guard. If the button was built before, return leaves the method at once.
  • Line 10 notes that the button is built now.
  • Line 20 prints Buttons: 1.
Real-life analogyOpening the shop each morning

Every morning, Asha unlocks the shop and switches on the lights. She does it again the next day, and nothing goes wrong. But she painted the sign over the door only once. If she painted it every morning, the paint would pile up.

In real life: Each new morning
In JavaScript: Each time the element joins the page
In real life: Unlocking the door and switching on the lights
In JavaScript: Work that is safe to run every time
In real life: Painting the sign over the door
In JavaScript: One-time setup, like the Serve button
In real life: The note that says the sign is done
In JavaScript: The #built guard

Why it matters: without a guard, every move adds another copy. The page looks broken after the first sort.

Moving an element with moveBefore()

Sometimes a move shouldn't count as leaving at all. Newer browsers have moveBefore(), a method that moves an element in one step. It works like insertBefore(). ready.moveBefore(badge, null) puts the badge at the end of ready.

On its own, moveBefore() still runs both callbacks, so older components keep working. Your class can ask for something else. If it has a connectedMoveCallback() method, the browser calls only that one for the move. Even an empty one works.

Moving a badge with moveBefore()Pop out in the code editor (opens in a new tab)HTML
<p id="brewing">Brewing: <tea-badge>Oolong</tea-badge></p><p id="ready">Ready: </p> <script src="tea-badge.js"></script> <script>  const badge = document.querySelector("tea-badge");  const ready = document.querySelector("#ready");  if ("moveBefore" in Element.prototype) {    ready.moveBefore(badge, null);  } else {    ready.append(badge);  }</script>
ResultLoading…
  • Lines 8 to 10 of tea-badge.js, the second tab, add connectedMoveCallback().
  • Line 9 of the page checks that this browser has moveBefore(). It's the feature check from lesson 1.2.
  • Line 10 moves the badge to Ready. The console prints Oolong joined the page from the upgrade, then Oolong moved.
  • Line 12 is for Safari, which has no moveBefore(). There, the badge leaves and joins again.

Take lines 8 to 10 out of tea-badge.js, and moveBefore() runs the other two callbacks again. Lesson 3.5, moving and adopting elements, goes deeper.

Two ways to move the badge. With append(): disconnectedCallback runs, then connectedCallback, so the badge leaves and joins again. With moveBefore() and a connectedMoveCallback: only connectedMoveCallback runs, and the badge stays on the page.append()disconnectedCallback()connectedCallback()leavesjoins againmoveBefore()connectedMoveCallback()stays on the page
append() takes the badge out and puts it back, so two callbacks run. moveBefore() with a connectedMoveCallback() runs only that one.

Here is everything the last three sections showed. Read each row across:

Which callbacks run
What the code doesWhich callbacks run
p.append(badge), for a badge that isn't on the page yet.connectedCallback() runs.
box.append(badge), for a box that isn't on the page.None. The badge isn't in a document.
badge.remove()disconnectedCallback() runs.
p.textContent = "Sold out", with badges inside p.disconnectedCallback() runs for each badge.
ready.append(badge), for a badge already on the page.disconnectedCallback() runs, then connectedCallback().
ready.moveBefore(badge, null), with a connectedMoveCallback().Only connectedMoveCallback() runs.
ready.moveBefore(badge, null), without one.disconnectedCallback() runs, then connectedCallback().
badge.hidden = trueNone. A hidden badge is still on the page.

How do you clean up in disconnectedCallback?

Back to Asha's ticking console. Ravi's timer starts a setInterval() in connectedCallback(). setInterval() runs a function again and again, here once a second. It belongs to the window, not to the element. So it keeps going after the element leaves.

Try both versions of the timer. Press Brew, wait two ticks, then press Serve:

Playground: does the timer stop?
A brewing timer you can add and servePop out in the code editor (opens in a new tab)HTML
<p id="shelf">Green tea: </p><button id="brew">Brew</button><button id="serve">Serve</button> <script src="tea-timer.js"></script> <script>  const timer = document.createElement("tea-timer");  const shelf = document.querySelector("#shelf");  document.querySelector("#brew").onclick = () => shelf.append(timer);  document.querySelector("#serve").onclick = () => timer.remove();</script>
ResultLoading…
Try it yourself
The ticks go on after Serve

Press Brew, wait two ticks, then press Serve. The timer leaves the page, but nothing stops its setInterval(). It keeps ticking for a timer nobody can see.

The page stays the same. Only tea-timer.js changes: open its tab to compare. Each choice runs in a fresh page.
  • Line 2 of the fixed tea-timer.js adds a private field, #interval.
  • Line 7 keeps the number that setInterval() gives back. That number names this timer.
  • Lines 14 to 16 are disconnectedCallback(). Line 15 passes the number to clearInterval(), which stops the timer.

With Ravi's first version, the ticks go on after Serve: Tick: 3 s, then Tick: 4 s. With the fixed one, they stop at Tick: 2 s. Press Brew again, and a new count starts from 0.

Memory is the second reason. Lit's docs say that disconnectedCallback() should make sure nothing outside still holds on to the element. Otherwise the browser can't free it.

Removing outside listeners with AbortController

A listener on document or window keeps going too, because the document is still there. Lit's docs name this as the most common job for the two callbacks: add outside listeners when the element joins, and remove them when it leaves.

You could remove each one with removeEventListener(). But that needs the exact same function you added, saved somewhere. An AbortController is simpler. It's an object with a signal and an abort() method. Pass the signal when you add a listener. Later, one call to abort() removes every listener that got that signal.

Ravi's shop shows a tip that closes when you click anywhere, or press any key. Click the page twice:

A tip with two listeners on one signalPop out in the code editor (opens in a new tab)HTML
<p>Teas: Green, Oolong, Black</p><tea-tip>Tip: brew green tea at 80°C. Click anywhere to close.</tea-tip> <script src="tea-tip.js"></script>
ResultLoading…

The page only shows the tip. Its class is in tea-tip.js, the second tab:

  • Line 5 makes a new controller each time the tip joins the page.
  • Line 6 takes its signal.
  • Lines 7 and 8 add two listeners on the document. Both get the same signal, in { signal }.
  • Line 12, in disconnectedCallback(), calls abort(). Both listeners are gone.
  • Lines 15 to 18 print Closing the tip and remove the tip.

The first click prints Closing the tip, and the tip disappears. Its disconnectedCallback() runs and aborts. The second click prints nothing. Without lines 11 to 13, the second click prints Closing the tip again, for a tip that's already gone.

One signal, one abort. In connectedCallback, the tip adds a click listener and a keydown listener, both with the same signal. In disconnectedCallback, one abort() call removes both listeners.connectedCallback()click listenersignalkeydown listenersignalboth use one signaldisconnectedCallback()abort()clickkeydownone abort() removes both
Both of the tip's listeners use one signal. When the tip leaves, one abort() removes both.
Real-life analogyOne switch on the power strip

Ravi's market stall has a lamp, a fan, and a radio, all plugged into one power strip. At closing time, he doesn't hunt for each plug. He flips the switch on the strip, and everything goes off at once.

In real life: The power strip
In JavaScript: The AbortController
In real life: Plugging a lamp into the strip
In JavaScript: Passing { signal } to addEventListener()
In real life: The lamp and the fan
In JavaScript: The click and keydown listeners
In real life: Flipping the strip's switch
In JavaScript: abort()

A new controller each time

Line 5 of tea-tip.js is inside connectedCallback(), not the constructor. That matters, because a signal stays aborted for good. addEventListener() skips a listener whose signal is already aborted:

An aborted signal adds nothingPop out in the code editor (opens in a new tab)JavaScript
const controller = new AbortController();
controller.abort();

document.addEventListener("click", () => console.log("Click"), {
  signal: controller.signal,
});
document.dispatchEvent(new Event("click"));
console.log("Aborted:", controller.signal.aborted);
  • Lines 1 and 2 make a controller and abort it.
  • Lines 4 to 6 add a click listener with the aborted signal.
  • Line 7 sends a click to the document. Nothing prints.
  • Line 8 prints Aborted: true.

So a controller made once, in the constructor, works only until the element first leaves. When the element comes back, its listeners are never added. Nolan Lawson describes the same trap: setup in the constructor, cleanup in disconnectedCallback(). Make a new controller each time the element joins. Exercise 4 has this bug.

A signal can stop more than listeners. signal.addEventListener("abort", …) runs a function when you abort. The kit's timer uses it to clear its interval, at the end of this lesson.

For more on signals, see Cancellation with AbortController. Now sort these lines. Which ones does disconnectedCallback() need to stop?

Stop it, or leave it?
  • setInterval(…)
  • document.addEventListener("click", …)
  • window.addEventListener("resize", …)
  • this.addEventListener("click", …)
  • A click listener on a button inside the element
  • this.textContent = "Ready"
Try it yourself
0 of 6 correct

Sort each line from a connectedCallback() by whether it needs cleanup when the element leaves.

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

In what order do parents and children connect?

A shelf with two cups inside joins the page. That's three elements joining at once. Whose callback runs first? Here is a shelf that leaves and comes back:

A shelf and two cups leave and come backPop out in the code editor (opens in a new tab)HTML
<tea-shelf id="shelf">  <tea-cup id="cup-1"></tea-cup>  <tea-cup id="cup-2"></tea-cup></tea-shelf> <script src="callbacks.js"></script> <script>  const shelf = document.querySelector("tea-shelf");  shelf.remove();  console.log("remove() is done");  document.body.append(shelf);  console.log("append() is done");</script>
ResultLoading…
  • Lines 1 to 4 put a shelf with two cups on the page. callbacks.js, the second tab, gives both tags the same two callbacks. They print the element's id.
  • Line 6 loads callbacks.js. Each element is upgraded and prints joined: the shelf, then cup-1, then cup-2.
  • Line 10 removes the shelf. The shelf, cup-1, and cup-2 print left, in that order. Then line 11 prints remove() is done.
  • Line 12 puts the shelf back. The three join in the same order, and line 13 prints append() is done.

Two rules show here.

First, the order is the order of the page, from top to bottom. The parent comes first, then its children. The DOM Standard calls it tree order, and it uses it both when elements join and when they leave.

Second, all the callbacks ran before the next line of the script. The HTML Standard calls them custom element reactions. While append() changes the page, the browser doesn't stop to run your code. It puts each callback in a queue. Just before append() returns to your script, it runs the queue, in order. For most code, it looks as if each callback ran at once.

The order of the callbacks when the shelf with two cups joins the page. First the shelf's connectedCallback, second cup-1's, third cup-2's. Fourth, the next line of the script prints append() is done.shelf1stcup-1cup-22nd3rdyour next lineappend() is done4th
The shelf comes first, then its cups in page order. All three callbacks run before append() returns, so append() is done prints fourth. Leaving goes in the same order.
Real-life analogyA host greets a family

A family of three walks into the tea shop. The host doesn't stop them in the doorway to greet each one. She waits until all three are inside. Then she greets the parent, then each child in turn. Only then does she show them to a table.

In real life: The family walking in together
In JavaScript: A shelf joining the page with its cups
In real life: The host's list of names
In JavaScript: The queue of callbacks
In real life: Greeting the parent, then each child
In JavaScript: The shelf's callback, then cup-1's, then cup-2's
In real life: Showing them to a table
In JavaScript: Your script's next line

The standard makes one more promise. Each element's own callbacks run in the order its changes happened. Across different elements, there's no fixed promise, because your callbacks can change the page too. Lesson 3.6, the custom element lifecycle in order, steps through the full timing.

Why can isConnected be false in connectedCallback?

Because the queue can fall behind. A callback is queued when the element joins. If something removes the element before the queue gets to it, the callback still runs. The HTML Standard warns about this case. Here is a tray that clears away its cup as soon as it's put down:

A tray removes its cup before the cup's callback runsPop out in the code editor (opens in a new tab)HTML
<p>Tray: </p> <script>  class TeaCup extends HTMLElement {    connectedCallback() {      console.log("Cup joined. isConnected:", this.isConnected);    }  }  class TeaTray extends HTMLElement {    connectedCallback() {      this.querySelector("tea-cup").remove();    }  }  customElements.define("tea-cup", TeaCup);  customElements.define("tea-tray", TeaTray);   const tray = document.createElement("tea-tray");  tray.append(document.createElement("tea-cup"));  document.querySelector("p").append(tray);</script>
ResultLoading…
  • Lines 4 to 8 are the cup. Its connectedCallback() prints isConnected.
  • Lines 9 to 13 are the tray. Its connectedCallback() removes the cup inside it.
  • Lines 17 and 18 make a tray with a cup.
  • Line 19 puts the tray on the page. Both elements join, so two callbacks are queued: the tray's, then the cup's.

The tray's callback runs first and removes the cup. Then the cup's callback runs, as queued. It prints Cup joined. isConnected: false. The cup was on the page when its callback was queued. It had left by the time the callback ran.

Real-life analogyThe waiter checks the seat before pouring

A guest at table 4 orders a pot of oolong. While it brews, she gets up and leaves. The waiter carries the pot over anyway. She looks at the seat before she pours. It's empty, so she takes the tea back.

In real life: Carrying over the tea someone ordered
In JavaScript: A queued callback, or work after an await
In real life: The guest who left while it brewed
In JavaScript: An element removed in the meantime
In real life: Looking at the seat first
In JavaScript: if (!this.isConnected) return;

So when connectedCallback() does work that only makes sense on the page, check first: if (!this.isConnected) return;. The HTML Standard also asks callbacks not to change the page around them, as the tray did. It leads to surprises like this one.

An async connectedCallback

The same check matters after an await. You can write async connectedCallback() and wait for data inside it. The browser calls it like any other method. Nolan Lawson points out that the browser ignores the promise it gives back. It doesn't wait. By the time the data arrives, the element may have left:

A menu that checks after it waitsPop out in the code editor (opens in a new tab)HTML
<p>Menu: </p> <script>  class TeaMenu extends HTMLElement {    async connectedCallback() {      await new Promise((done) => setTimeout(done, 300));      if (!this.isConnected) {        console.log("Gone before the menu loaded");        return;      }      this.textContent = "Green, Oolong, Black";    }  }  customElements.define("tea-menu", TeaMenu);   const menu = document.createElement("tea-menu");  document.querySelector("p").append(menu);  console.log("append() is done");  menu.remove();</script>
ResultLoading…
  • Line 5 makes the callback async.
  • Line 6 waits 300 ms. It stands in for loading the menu from a server.
  • Lines 7 to 10 check isConnected after the wait. They stop if the menu has left.
  • Line 17 adds the menu, and its callback starts. Line 18 prints append() is done at once.
  • Line 19 removes the menu before the wait is over.

A moment later, the console prints Gone before the menu loaded. Without lines 7 to 10, the menu would fill itself in while off the page. In a real component, that might be a listener added after the element left. Nothing would ever remove it.

Adding a brewing timer to the tea kit

Ravi adds the timer to the tea kit, so every page can use it. The kit's timer counts down from its seconds attribute and shows Ready at 0. It uses everything from this lesson. Press Brew, then move it both ways:

The tea kit's timer, moved two waysPop out in the code editor (opens in a new tab)HTML
<script type="importmap">  { "imports": { "tea-kit/": "./tea-kit/" } }</script> <p id="brewing">Brewing: </p><p id="ready">Ready: </p><button id="brew">Brew</button><button id="append">Move with append()</button><button id="move">Move with moveBefore()</button> <script type="module">  import "tea-kit/index.js";   const timer = document.createElement("tea-timer");  timer.setAttribute("seconds", "5");  const [brewing, ready] = document.querySelectorAll("p");  const other = () => (timer.parentNode === brewing ? ready : brewing);  document.querySelector("#brew").onclick = () => brewing.append(timer);  document.querySelector("#append").onclick = () => other().append(timer);  document.querySelector("#move").onclick = () => other().moveBefore(timer, null);  document.querySelector("#move").disabled = !("moveBefore" in Element.prototype);</script>
ResultLoading…
  • Lines 1 to 3 are the import map from lesson 1.4. Line 12 loads the whole kit, now with tea-timer.js.
  • Lines 14 and 15 make a timer by name and give it 5 seconds.
  • Line 18 adds it to Brewing. Lines 19 and 20 move it to the other shelf, with append() or moveBefore().
  • Line 21 turns off the moveBefore() button in browsers that don't have it.

Now open the tea-kit/tea-timer.js tab:

  • Line 5 makes a new AbortController each time the timer joins.
  • Line 6 reads seconds here, not in the constructor, as lesson 3.2 taught.
  • Lines 8 to 12 count down once a second and stop at Ready.
  • Line 13 clears the interval when the signal aborts.
  • Line 17 aborts in disconnectedCallback().
  • Line 20 is an empty connectedMoveCallback().

Press Brew and wait two seconds: the timer shows 3 s. Move it with append(). It leaves and joins, so it starts again at 5 s. Wait a second, then move it with moveBefore(). It stays at 4 s and keeps counting. The empty connectedMoveCallback() tells Chrome and Firefox that a move isn't a reset. In Safari, that button is off.

The kit's first files from lesson 3.1 stay as they are. They only set textContent, which is safe to repeat. The kit gains three rules:

  • Whatever connectedCallback() starts, disconnectedCallback() stops.
  • Each connection gets a new AbortController, and one signal stops its listeners and timers.
  • Setup that must happen only once gets a guard.

Asha puts the kit's timer in her shop. Now, when she serves a tea, its timer stops ticking.

Common mix-ups

  • "connectedCallback() runs once, like the constructor." No. It runs each time the element joins the page. Every move runs it again.
  • "disconnectedCallback() means the element is gone for good." No. It can come back. Undo everything, and expect connectedCallback() to set it up again.
  • "Set things up in the constructor, and clean up in disconnectedCallback()." No. The constructor runs once. After the first trip off the page, the cleanup has run, and the setup never comes back.
  • "Hiding an element runs disconnectedCallback()." No. A hidden element is still in the document. Only leaving it counts.
  • "One AbortController, made in the constructor, is enough." No. After the first abort(), its signal stays aborted. Listeners added with it later are skipped.
  • "An async connectedCallback() makes the browser wait." No. The browser ignores the promise. The element can leave before your await is over.
  • "Every listener needs removing." No. Listeners on the element itself, or on elements inside it, go away with it. Only outside ones need cleanup.
  • "Inside connectedCallback(), isConnected is always true." No. A queued callback can run after the element has left.

Practice exercises

Answer first, then use the hints. The solutions run live, so you can check yourself.

Exercise 1 · Warm-upMoving a box moves the badge

How many times does the console print Organic joined the page?

<p id="a">A: </p>
<p id="b">B: </p>

<script>
  class TeaBadge extends HTMLElement {
    connectedCallback() {
      console.log(`${this.textContent} joined the page`);
    }
    disconnectedCallback() {
      console.log(`${this.textContent} left the page`);
    }
  }
  customElements.define("tea-badge", TeaBadge);

  const badge = document.createElement("tea-badge");
  badge.textContent = "Organic";
  const box = document.createElement("div");
  box.append(badge);
  document.querySelector("#a").append(box);
  document.querySelector("#b").append(box);
  badge.remove();
</script>

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

    Exercise 2 · Warm-upOne shelf moved into another

    What does the console print last?

    <tea-shelf id="top">
      <tea-cup id="green"></tea-cup>
    </tea-shelf>
    <tea-shelf id="bottom">
      <tea-cup id="black"></tea-cup>
    </tea-shelf>
    
    <script>
      class Logged extends HTMLElement {
        connectedCallback() { console.log(`${this.id} joined`); }
        disconnectedCallback() { console.log(`${this.id} left`); }
      }
      customElements.define("tea-shelf", class extends Logged {});
      customElements.define("tea-cup", class extends Logged {});
    
      const bottom = document.querySelector("#bottom");
      document.querySelector("#top").append(bottom);
    </script>

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

      Exercise 3 · PracticeFind the bug in the new note

      What does line 16 print? Then fix the class so the note is added only once.

      <p id="new">New: <tea-note>Oolong</tea-note></p><p id="all">All teas: </p> <script>  class TeaNote extends HTMLElement {    connectedCallback() {      const small = document.createElement("small");      small.textContent = " (new)";      this.append(small);    }  }  customElements.define("tea-note", TeaNote);   const note = document.querySelector("tea-note");  document.querySelector("#all").append(note);  console.log(note.textContent);</script>
      ResultLoading…

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

        Exercise 4 · PracticeFind the bug in the tip's controller

        Click the page once. What does the console print? Then fix it.

        <p>Click anywhere on this page.</p><tea-tip>Tip: brew green tea at 80°C.</tea-tip> <script>  class TeaTip extends HTMLElement {    #controller = new AbortController();     connectedCallback() {      const signal = this.#controller.signal;      document.addEventListener("click", () => console.log("Tip heard a click"), { signal });    }     disconnectedCallback() {      this.#controller.abort();    }  }  customElements.define("tea-tip", TeaTip);   const tip = document.querySelector("tea-tip");  tip.remove();  document.body.append(tip);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeStop the timer with a signal

          Follow the steps in the comments. Then press Brew, wait two seconds, and press Serve. How many Tick lines print after Serve?

          <p id="shelf">Green tea: </p><button id="brew">Brew</button><button id="serve">Serve</button> <script>  class TeaTimer extends HTMLElement {    // 1. Add a #controller field.    connectedCallback() {      // 2. Make a new AbortController here.      let seconds = 0;      const interval = setInterval(() => {        seconds += 1;        console.log(`Tick: ${seconds} s`);      }, 1000);      // 3. Clear the interval when the signal aborts.    }    // 4. Abort the controller in disconnectedCallback().  }  customElements.define("tea-timer", TeaTimer);   const timer = document.createElement("tea-timer");  const shelf = document.querySelector("#shelf");  document.querySelector("#brew").onclick = () => shelf.append(timer);  document.querySelector("#serve").onclick = () => timer.remove();</script>
          ResultLoading…

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

            Exercise 6 · ChallengeCount the listeners

            Click the page once. How many lines does the console print? Then make it print one.

            <p id="a">A: <tea-tip>Tip: brew green tea at 80°C.</tea-tip></p><p id="b">B: </p> <script>  class TeaTip extends HTMLElement {    connectedCallback() {      document.addEventListener("click", () => console.log("Tip heard a click"));    }  }  customElements.define("tea-tip", TeaTip);   const tip = document.querySelector("tea-tip");  document.querySelector("#b").append(tip);  document.querySelector("#a").append(tip);</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask when the element joined, when it left, and what is still running.

              The connectedCallback quiz · 8 questionsScore: first tries count
              1. Question 1 of 8When does the browser call an element's connectedCallback()?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this page print, from lines 12 and 13?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <p>Teas: </p>
                
                <script>
                  class TeaBadge extends HTMLElement {
                    connectedCallback() { console.log("joined"); }
                    disconnectedCallback() { console.log("left"); }
                  }
                  customElements.define("tea-badge", TeaBadge);
                
                  const badge = document.createElement("tea-badge");
                  const p = document.querySelector("p");
                  p.append(badge);
                  p.append(badge);
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 8Which line belongs in disconnectedCallback()?

                Choose an answer to see the explanation.

              4. Question 4 of 8Why does connectedCallback() make a new AbortController each time?

                Choose an answer to see the explanation.

              5. Question 5 of 8A tray's connectedCallback() removes its cup. Then the cup's connectedCallback() prints this.isConnected. What does it print, and why?

                Choose an answer to see the explanation.

              6. Question 6 of 8You add a shelf that holds two cups. In what order do the three connectedCallback() calls run?

                Choose an answer to see the explanation.

              7. Question 7 of 8An element has a connectedMoveCallback(). You move it with moveBefore(). Which callbacks run?

                Choose an answer to see the explanation.

              8. Question 8 of 8What happens when connectedCallback() is async and awaits some data?

                Choose an answer to see the explanation.

              Key takeaways

              • connectedCallback() runs each time the element joins a document. disconnectedCallback() runs each time it leaves.
              • A parent off the page isn't enough. isConnected tells you whether the element is in a document.
              • A move with append() runs both callbacks. A move with moveBefore() runs only connectedMoveCallback(), if the class has one.
              • Setup that must happen once needs a guard, because the callbacks run many times.
              • Stop timers and remove outside listeners when the element leaves. One AbortController per connection does both.
              • Callbacks are queued: the parent first, then its children in page order, all before the DOM method returns. Check isConnected when work might come too late.

              Remember the one-liner.
              Start it when the element joins the page, stop it when it leaves, and expect both to happen many times.

              Sources

              The facts on this page come from these standards and docs:

              Coming next: Reacting to attributes. List the attributes you care about, and react when they change.

              CompleteFrontend Clear concepts. Working examples.