connectedCallback: Element Insertion
You'll learn how to run setup logic automatically when your custom element is added to the DOM.
What is connectedCallback?
When you define a custom element, you often need to perform initialization tasks — setting up event listeners, fetching data, rendering initial content, or modifying attributes. The connectedCallback() lifecycle method is your "component mount" hook: it fires automatically every time your custom element is inserted into the DOM.
Think of it like a housewarming party that happens automatically whenever someone moves into a new home. The moment your element "moves into" the document, connectedCallback() runs.
How It Works
Inside your custom element class, define a connectedCallback() method. This method runs:
- When the element is first inserted via JavaScript (
appendChild,insertBefore, etc.) - When the parser encounters your element in HTML
- Every time the element is moved to a new location in the DOM
class MyCounter extends HTMLElement {
connectedCallback() {
// Setup logic runs here
this.count = 0;
this.innerHTML = `<button>Count: ${this.count}</button>`;
this.querySelector('button').addEventListener('click', () => {
this.count++;
this.querySelector('button').textContent = `Count: ${this.count}`;
});
}
}
customElements.define('my-counter', MyCounter);
When to Use It
Use connectedCallback() for:
- Rendering initial content
- Setting up event listeners
- Reading attributes
- Starting timers or animations
- Fetching data
Key Takeaway: connectedCallback() is your custom element's initialization point — it runs automatically when the element enters the DOM, making it the perfect place for setup logic.