Lifecycle hooks and context
Custom elements receive JavaScript calls as they are attached to and detached from a page. These lifecycle callbacks let an element react to where it lives — which is the basis for building context-aware components. The four callbacks are:
connectedCallback: fires when the custom element is attached.disconnectedCallback: fires when the element is removed from the document.adoptedCallback: fires when the element is added to a new document.attributeChangedCallback: fires when an observed attribute is changed, added or removed.
A component that reads its surroundings

The example component is <postapocalyptic-person>. Whether a person is a human or a zombie is determined by a class — .human or .zombie — on the component's parent element. The element gets a shadowRoot so an image can be attached to match that classification.
customElements.define(
"postapocalyptic-person",
class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: "open" });
}
}
The markup used to exercise it:
<div class="humans">
<postapocalyptic-person></postapocalyptic-person>
</div>
<div class="zombies">
<postapocalyptic-person></postapocalyptic-person>
</div>
Populating on attach
Loading a <postapocalyptic-person> on the page triggers connectedCallback(), which outputs a human image or a zombie image depending on the parent's class.
connectedCallback() {
let image = document.createElement("img");
if (this.parentNode.classList.contains("humans")) {
image.src = "https://assets.codepen.io/1804713/lady.png";
this.shadowRoot.appendChild(image);
} else if (this.parentNode.classList.contains("zombies")) {
image.src = "https://assets.codepen.io/1804713/ladyz.png";
this.shadowRoot.appendChild(image);
}
}
One caution: connectedCallback fires more often than you might expect — it runs whenever the element is moved, and can even run after the node has been disconnected, which can be costly. this.isConnected reports whether the element is actually connected.
Tallying additions
Two buttons extend the example: one adds a <postapocalyptic-person>, deciding human or zombie by coin flip; the other removes a random one. Humans and zombies in view are counted as we go.
<div class="btns">
<button id="addbtn">Add Person</button>
<button id="rmvbtn">Remove Person</button>
<span class="counts">
Humans: <span id="human-count">0</span>
Zombies: <span id="zombie-count">0</span>
</span>
</div>
The buttons' behavior:
let zombienest = document.querySelector(".zombies"),
humancamp = document.querySelector(".humans");
document.getElementById("addbtn").addEventListener("click", function () {
// Flips a "coin" and adds either a zombie or a human
if (Math.random() > 0.5) {
zombienest.appendChild(document.createElement("postapocalyptic-person"));
} else {
humancamp.appendChild(document.createElement("postapocalyptic-person"));
}
});
document.getElementById("rmvbtn").addEventListener("click", function () {
// Flips a "coin" and removes either a zombie or a human
// A console message is logged if no more are available to remove.
if (Math.random() > 0.5) {
if (zombienest.lastElementChild) {
zombienest.lastElementChild.remove();
} else {
console.log("No more zombies to remove");
}
} else {
if (humancamp.lastElementChild) {
humancamp.lastElementChild.remove();
} else {
console.log("No more humans to remove");
}
}
});
The counting logic lives in connectedCallback():
connectedCallback() {
let image = document.createElement("img");
if (this.parentNode.classList.contains("humans")) {
image.src = "https://assets.codepen.io/1804713/lady.png";
this.shadowRoot.appendChild(image);
// Get the existing human count.
let humancount = document.getElementById("human-count");
// Increment it
humancount.innerHTML = parseInt(humancount.textContent) + 1;
} else if (this.parentNode.classList.contains("zombies")) {
image.src = "https://assets.codepen.io/1804713/ladyz.png";
this.shadowRoot.appendChild(image);
// Get the existing zombie count.
let zombiecount = document.getElementById("zombie-count");
// Increment it
zombiecount.innerHTML = parseInt(zombiecount.textContent) + 1;
}
}
Decrementing on removal
disconnectedCallback() decrements the counts as people are removed. The parent's class can't be read at that point — the parent element is already gone. Setting an attribute or property on the element would work, but since the image's src attribute is already derived from the parent, it can serve as the proxy for telling human from zombie.
disconnectedCallback() {
let image = this.shadowRoot.querySelector('img');
// Test for the human image
if (image.src == "https://assets.codepen.io/1804713/lady.png") {
let humancount = document.getElementById("human-count");
humancount.innerHTML = parseInt(humancount.textContent) - 1; // Decrement count
// Test for the zombie image
} else if (image.src == "https://assets.codepen.io/1804713/ladyz.png") {
let zombiecount = document.getElementById("zombie-count");
zombiecount.innerHTML = parseInt(zombiecount.textContent) - 1; // Decrement count
}
}
Moving components between documents
The example adds one more wrinkle: any human or zombie might secretly be a clown. When a suspected clown is found, it is sent to a separate document inside an <iframe>. Moving a node there does not destroy and recreate it; the node is adopted and connected, calling adoptedCallback first and then connectedCallback.
The iframe document needs only a body with a .clowns class. As long as it stays embedded in the main document rather than being viewed separately, the <postapocalyptic-person> instantiation code is unnecessary. The layout provides one space for humans, another for zombies, and the iframe holding the clowns.
<div class="btns">
<button id="addbtn">Add Person</button>
<button id="jailbtn">Jail Potential Clown</button>
</div>
<div class="humans">
<postapocalyptic-person></postapocalyptic-person>
</div>
<div class="zombies">
<postapocalyptic-person></postapocalyptic-person>
</div>
<iframe class="clowniframeoffun” src="adoptedCallback-iframe.html">
</iframe>
"Add Person" behaves as before, flipping a digital coin to insert a human or a zombie. "Jail Potential Clown" flips another coin, picks a human or a zombie, and hands it to the iframe.
document.getElementById("jailbtn").addEventListener("click", function () {
if (Math.random() > 0.5) {
let human = humancamp.querySelector('postapocalyptic-person');
if (human) {
clowncollege.contentDocument.querySelector('body').appendChild(document.adoptNode(human));
} else {
console.log("No more potential clowns at the human camp");
}
} else {
let zombie = zombienest.querySelector('postapocalyptic-person');
if (zombie) {
clowncollege.contentDocument.querySelector('body').appendChild(document.adoptNode(zombie));
} else {
console.log("No more potential clowns at the zombie nest");
}
}
});
Inside adoptedCallback, the clown's type is determined from its current image and the image is swapped to match. connectedCallback runs afterward; it has nothing it needs to do there and does not interfere with the change, so it stays as is.
adoptedCallback() {
let image = this.shadowRoot.querySelector("img");
if (this.parentNode.dataset.type == "clowns") {
if (image.src.indexOf("lady.png") != -1) {
// Sometimes, the full URL path including the domain is saved in `image.src`.
// Using `indexOf` allows us to skip the unnecessary bits.
image.src = "ladyc.png";
this.shadowRoot.appendChild(image);
} else if (image.src.indexOf("ladyz.png") != -1) {
image.src = "ladyzc.png";
this.shadowRoot.appendChild(image);
}
}
}
Observed attributes
attributeChangedCallback differs from the other three: it only fires for attributes the element observes. Adding an observedAttributes() function to the custom element's class that returns an array of attribute names enables it.
static get observedAttributes() {
return [“attribute-name”];
}
Once an attribute in that list is added, removed or changed, the callback fires. A "clown detector" uses this to expose disguised clowns: clicking "Reveal Clowns" applies data-clown="true" to the component, and the resulting callback updates the image to reveal the clown.
The callback receives three parameters:
- the attribute name
- the previous value
- the new value
That makes it possible to respond to the size of a change or to a transition between two states.
attributeChangedCallback(name, oldValue, newValue) {
let image = this.shadowRoot.querySelector("img");
// Ensures that `data-clown` was the attribute that changed,
// that its value is true, and that it had an image in its `shadowRoot`
if (name="data-clown" && this.dataset.clown && image) {
// Setting and updating the counts of humans, zombies,
// and clowns on the page
let clowncount = document.getElementById("clown-count"),
humancount = document.getElementById("human-count"),
zombiecount = document.getElementById("zombie-count");
if (image.src.indexOf("lady.png") != -1) {
image.src = "https://assets.codepen.io/1804713/ladyc.png";
this.shadowRoot.appendChild(image);
// Update counts
clowncount.innerHTML = parseInt(clowncount.textContent) + 1;
humancount.innerHTML = parseInt(humancount.textContent) - 1;
} else if (image.src.indexOf("ladyz.png") != -1) {
image.src = "https://assets.codepen.io/1804713/ladyzc.png";
this.shadowRoot.appendChild(image);
// Update counts
clowncount.innerHTML = parseInt(clowncount.textContent) + 1;
zombiecount.innerHTML = parseInt(zombiecount.textContent) - 1;
}
}
}


