0Pricing
JavaScript Academy · Lesson

Lifecycle Callbacks

Hook into connected, disconnected, and attribute changes.

Lifecycle Callbacks is a free JavaScript 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 JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Element Lifecycle

Custom elements have a defined lifecycle. The browser calls special methods on your class at key moments:

  • connectedCallback — added to the DOM
  • disconnectedCallback — removed from the DOM
  • attributeChangedCallback — an observed attribute changes
  • adoptedCallback — moved to a new document

connectedCallback

connectedCallback runs every time the element is inserted into the document. This is the ideal place to render content, fetch data, or attach global listeners.

It can fire multiple times if the element is moved around.

class StatusBadge extends HTMLElement {
  connectedCallback() {
    this.textContent = 'Online';
    console.log('badge added to page');
  }
}
customElements.define('status-badge', StatusBadge);

disconnectedCallback

disconnectedCallback runs when the element is removed from the DOM. Use it to clean up: remove global listeners, cancel timers, or close connections to avoid memory leaks.

class ClockWidget extends HTMLElement {
  connectedCallback() {
    this.timer = setInterval(() => {
      this.textContent = new Date().toLocaleTimeString();
    }, 1000);
  }
  disconnectedCallback() {
    clearInterval(this.timer); // cleanup
  }
}
customElements.define('clock-widget', ClockWidget);

Observing Attributes

To react to attribute changes you must declare which attributes to watch with a static observedAttributes getter that returns an array of names.

Only listed attributes trigger attributeChangedCallback.

class AvatarImage extends HTMLElement {
  static get observedAttributes() {
    return ['src', 'alt'];
  }
}
customElements.define('avatar-image', AvatarImage);

attributeChangedCallback

When an observed attribute is added, removed, or changed, the browser calls attributeChangedCallback(name, oldValue, newValue). Use it to keep your rendered output in sync with attributes.

class AvatarImage extends HTMLElement {
  static get observedAttributes() { return ['src']; }
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === 'src') {
      this.innerHTML = '<img src="' + newValue + '">';
    }
  }
}
customElements.define('avatar-image', AvatarImage);

Callback Arguments

attributeChangedCallback receives three arguments:

  • name — which attribute changed
  • oldValue — previous value (null if newly added)
  • newValue — new value (null if removed)

Compare old and new to skip unnecessary work.

attributeChangedCallback(name, oldValue, newValue) {
  if (oldValue === newValue) return; // no real change
  console.log(name + ' changed to ' + newValue);
}

Initial Attribute Calls

If an element already has an observed attribute when it is upgraded, attributeChangedCallback fires once for each before connectedCallback. This lets you initialize from markup automatically.

// <avatar-image src="a.png"></avatar-image>
// On upgrade: attributeChangedCallback('src', null, 'a.png')
// runs BEFORE connectedCallback.

Reflecting Properties to Attributes

A common pattern is to expose a JavaScript property that reads and writes the attribute. This keeps the API ergonomic while staying in sync.

class AvatarImage extends HTMLElement {
  static get observedAttributes() { return ['src']; }
  get src() { return this.getAttribute('src'); }
  set src(value) { this.setAttribute('src', value); }
}
customElements.define('avatar-image', AvatarImage);

adoptedCallback

adoptedCallback runs when an element is moved from one document to another (for example, into an iframe via document.adoptNode). It is rarely needed but completes the lifecycle.

class PortableWidget extends HTMLElement {
  adoptedCallback() {
    console.log('moved to a new document');
  }
}
customElements.define('portable-widget', PortableWidget);

Lifecycle Order

For an element written directly in HTML the typical order is:

  • constructor
  • attributeChangedCallback (once per observed attribute present)
  • connectedCallback

And later, on removal, disconnectedCallback.

Putting It Together

A complete element wires up all the pieces: observe attributes, render on connect, sync on attribute change, and clean up on disconnect.

class GreetUser extends HTMLElement {
  static get observedAttributes() { return ['name']; }
  connectedCallback() { this.render(); }
  attributeChangedCallback() { this.render(); }
  render() {
    const name = this.getAttribute('name') || 'Guest';
    this.textContent = 'Hello, ' + name;
  }
}
customElements.define('greet-user', GreetUser);

Quick Check

Test your knowledge of lifecycle callbacks.

Recap

You learned the custom element lifecycle:

  • connectedCallback runs on insertion — render here.
  • disconnectedCallback runs on removal — clean up here.
  • observedAttributes declares which attributes to watch.
  • attributeChangedCallback(name, old, new) reacts to changes.
  • adoptedCallback handles cross-document moves.

Next, we encapsulate styles and markup with the Shadow DOM.

Frequently asked questions

Is the “Lifecycle Callbacks” lesson free?

Yes — the full text of “Lifecycle Callbacks” is free to read here on the web, and the JavaScript 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 JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Lifecycle Callbacks”?

Hook into connected, disconnected, and attribute changes. You practise JavaScript 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 JavaScript Academy?

No prior experience is required. JavaScript 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 “Lifecycle Callbacks” 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 JavaScript Academy lesson?

Yes. Every JavaScript 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

  1. Defining Custom Elements
  2. Lifecycle Callbacks
  3. Shadow DOM and Encapsulation
  4. Templates and Slots
← Back to JavaScript Academy