The connectedCallback and disconnectedCallback
Run code when a custom element is added or removed from the DOM.
The connectedCallback and disconnectedCallback is a free HTML Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Element Lifecycle Callbacks
Custom elements expose four lifecycle hooks: connectedCallback, disconnectedCallback, attributeChangedCallback, and adoptedCallback. They mirror the well-known mount/unmount/update points of any component model.
connectedCallback Fires on Insertion
connectedCallback runs every time the element is inserted into the DOM tree. This is the right place to read attributes, render content, attach event listeners, and start any timers or subscriptions.
class Timer extends HTMLElement {
connectedCallback() {
this.start = Date.now();
this.interval = setInterval(() => this.render(), 1000);
this.render();
}
render() {
this.textContent = Math.floor((Date.now() - this.start) / 1000) + "s";
}
}It May Fire More Than Once
If the element is removed and re-inserted, connectedCallback fires again on each insertion. Idempotency matters — guard initialization that should only happen once with a flag, or do full setup every time and let disconnectedCallback tear down.
disconnectedCallback Fires on Removal
disconnectedCallback runs when the element is removed from the DOM. This is where you stop intervals, abort fetches, remove document-level listeners and release any resource that would otherwise leak.
disconnectedCallback() {
clearInterval(this.interval);
window.removeEventListener("resize", this.onResize);
}Garbage Collection and Listeners
An element with an active interval, document listener, or unresolved Promise will not be garbage collected even after disconnection. Always pair every subscription created in connectedCallback with cleanup in disconnectedCallback.
Reconnection After Move
Moving an element with parentB.appendChild(element) first removes it from parentA, then inserts into parentB. The browser fires disconnectedCallback then connectedCallback. Plan for transient teardown/setup during moves.
Initial Connection Timing
For an element written directly in HTML, connectedCallback fires during initial parsing, after the constructor. Attributes are already parsed at this point, so reading this.getAttribute("name") here returns the markup value.
Children May Not Be Parsed Yet
For an element with children declared in HTML, the children may not be in the DOM yet when connectedCallback fires (the parser is still going). Use a MutationObserver or read children inside requestAnimationFrame if you need access to declared children.
adoptedCallback
adoptedCallback fires when an element is moved to a new document (typically via document.adoptNode). Most apps never use this — it matters mainly for components moved between iframes.
Pairing With AbortController
A clean pattern: create an AbortController in connectedCallback, pass { signal: this.controller.signal } to every addEventListener and fetch, then call this.controller.abort() in disconnectedCallback to remove all of them at once.
Avoid Heavy Work in Constructor
The constructor runs even when the element is created via document.createElement and never inserted. Restrict the constructor to setting initial property values; defer rendering, fetching and listener attachment to connectedCallback.
Knowledge Check
Why should subscriptions and timers be set up in connectedCallback rather than in the element's constructor?
Summary
connectedCallback (insertion) and disconnectedCallback (removal) bookend the element's active lifetime. Set up listeners, intervals and fetches in connectedCallback; tear them down in disconnectedCallback to prevent leaks. Both may fire multiple times — use AbortController for clean batched cleanup.
Frequently asked questions
Is the “The connectedCallback and disconnectedCallback” lesson free?
Yes — the full text of “The connectedCallback and disconnectedCallback” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.
What will I learn in “The connectedCallback and disconnectedCallback”?
Run code when a custom element is added or removed from the DOM. You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start HTML Academy?
No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The connectedCallback and disconnectedCallback” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this HTML Academy lesson?
Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining Elements with customElements.define
- The connectedCallback and disconnectedCallback
- Observed Attributes and attributeChangedCallback
- Extending Built-in Elements