0Pricing
JavaScript Academy · Lesson

Lifecycle Callbacks

Hook into connected, disconnected, and attribute changes.

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);

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