0Pricing
HTML Academy · Lesson

The connectedCallback and disconnectedCallback

Run code when a custom element is added or removed from the DOM.

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";
  }
}

All lessons in this course

  1. Defining Elements with customElements.define
  2. The connectedCallback and disconnectedCallback
  3. Observed Attributes and attributeChangedCallback
  4. Extending Built-in Elements
← Back to HTML Academy