liveBook · Manning

Attributechangedcallback

As explained in Web Components in Action

attributeChangedCallback is a custom-element lifecycle callback invoked when an observed HTML attribute is added, removed, or changed.

attributeChangedCallback lets a custom element react when a watched HTML attribute is added, removed, or changed. It turns declarative markup changes into component behavior, such as rerunning a search or changing a layout. section 3.0 section 3.4

Wire the callback into a custom element in three steps:

  • Declare the attributes to monitor with static get observedAttributes(), such as ['searchterm']. section 3.4
  • Define attributeChangedCallback(name, oldValue, newValue); the browser supplies the changed attribute name and its previous and current values. section 3.4
  • Branch on name and update only the relevant behavior; an unobserved attribute does not trigger this callback. section 3.4
  • Account for startup ordering: initial attributes can invoke attributeChangedCallback before connectedCallback, so dependent DOM nodes may not exist yet. section 3.6

Rerun a search when searchterm changes

A text input updates the component with setAttribute('searchterm', event.target.value). The observed attribute then invokes attributeChangedCallback, which checks for 'searchterm' and calls doSearch(). Removing the separate startup search avoids overlapping requests when both lifecycle callbacks would run. section 3.4

Drive a slider and card layout

A slider observes value and backgroundcolor, dispatching each new value to refreshSlider or setColor. A business-card component observes layout, clears its contents, clones the matching template, and appends it when the attribute changes. section 3.6 section 7.3

Listing 3.12. AttributeChangedCallback to listen for changes to our searchterm
attributeChangedCallback(name, oldval, newval) {
   if (name === 'searchterm') {
       this.doSearch();
   }
}

Open the minimal callback that reruns a component search when searchterm changes. section 3.4

How Web Components in Action covers it

How deep it goes
Explains parameters, attribute filtering, startup ordering, and component examples, while deferring broader lifecycle coverage.
Examples
Demonstrates search inputs, sliders, reflected properties, and business-card layouts selected from HTML templates.
What it assumes
Assumes basic custom-element and lifecycle knowledge while introducing observedAttributes, attribute access, and attribute-to-property reflection.
What you can do after
Build custom elements that respond to selected attribute changes and connect those changes to searches, visual updates, or templates.
How it connects
Connects custom elements with connectedCallback, observedAttributes, HTML attributes, reflection, getters, setters, and templates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.