Sub topic 15
Reacting to skipped state with contentvisibilityautostatechange
This chapter assumes you know content-visibility: auto and contain-intrinsic-size from the earlier chapters. You should also be comfortable with addEventListener and with the idea that a skipped element has no layout or paint of its own.
Why you may need to know about skipping
With content-visibility: auto, the browser decides when an element's contents are skipped. You do not control that decision, and CSS gives you no hook to observe it. Most pages never need one. Some do:
- A section holds a running animation, a video, or a
requestAnimationFrameloop. Work for content nobody can see is wasted. - A section holds a widget that is expensive to build, such as a chart or a map. You would like to build it only when the section is about to be drawn.
- You want to log how often users actually reach each part of a long page.
The contentvisibilityautostatechange event covers these cases. The browser fires it at an element with content-visibility: auto each time it starts or stops skipping that element's contents.
The event
The event object is a ContentVisibilityAutoStateChangeEvent. It adds one property to a normal event:
| Property | Type | Meaning |
|---|---|---|
| `skipped` | boolean | `true` if the element's contents are now skipped, `false` if they are now rendered |
Key facts about when and where it fires:
- It fires only on elements whose computed
content-visibilityisauto. Elements withhiddenorvisiblenever fire it, because the browser does not make the skip decision for them. - The browser skips contents only while they are not relevant to the user. Contents count as relevant when they are on screen or near the viewport, hold focus, hold a selection, or are in the top layer. The event reports changes in that relevance.
- Attach the listener to the element itself. Do not rely on a parent listener to catch events from many children.
- The event is delivered during the browser's rendering update, not synchronously with your scroll handler. Keep the handler short.
A minimal listener
This example logs each state change. The data-name attribute is only there to label the output.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>State change demo</title>
<style>
.chunk {
content-visibility: auto;
contain-intrinsic-size: auto 800px;
border-bottom: 1px solid #ccc;
}
</style>
</head>
<body>
<section class="chunk" data-name="one"><p>First section</p></section>
<section class="chunk" data-name="two"><p>Second section</p></section>
<section class="chunk" data-name="three"><p>Third section</p></section>
<script>
document.querySelectorAll('.chunk').forEach((el) => {
el.addEventListener('contentvisibilityautostatechange', (event) => {
console.log(el.dataset.name, event.skipped ? 'skipped' : 'rendered');
});
});
</script>
</body>
</html>Scroll the page with the console open. Each section logs rendered as it approaches the viewport and skipped once it has moved far enough away. The exact distance is chosen by the browser, so do not hard-code assumptions about it.
The life of an element
The element moves between two states. Your handler runs on each transition.
An element that starts near the viewport may be rendered from the first frame. Handle both initial states. Do not assume the first event you see is skipped: false.
Example: pausing work for skipped content
This page has sections with a canvas animation. The animation stops while its section is skipped and resumes when it renders again.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pause animation while skipped</title>
<style>
.panel {
content-visibility: auto;
contain-intrinsic-size: auto 400px;
margin-block: 2rem;
}
canvas { width: 300px; height: 150px; background: #eef; }
</style>
</head>
<body>
<section class="panel"><canvas width="300" height="150"></canvas></section>
<section class="panel"><canvas width="300" height="150"></canvas></section>
<script>
function startAnimation(canvas) {
const ctx = canvas.getContext('2d');
let frameId = 0;
let x = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 60, 30, 30);
x = (x + 2) % canvas.width;
frameId = requestAnimationFrame(draw);
}
draw();
return () => cancelAnimationFrame(frameId);
}
document.querySelectorAll('.panel').forEach((panel) => {
const canvas = panel.querySelector('canvas');
let stop = null;
panel.addEventListener('contentvisibilityautostatechange', (event) => {
if (event.skipped) {
if (stop) { stop(); stop = null; }
} else if (!stop) {
stop = startAnimation(canvas);
}
});
});
</script>
</body>
</html>The stop variable guards against starting two loops if the browser reports skipped: false twice in a row.
Choosing the work to do in the handler
| Goal | Good use of the event | Better alternative |
|---|---|---|
| Pause animations or timers | Yes. This is the main use case | None. The browser does not stop your JavaScript for you |
| Build an expensive widget lazily | Yes, but only the first time | `IntersectionObserver` if you need a larger margin than the browser's |
| Analytics for "section reached" | Possible, but relevance includes focus and find-in-page | `IntersectionObserver` for true visibility |
| Measure layout of descendants | No. Skipped contents have no up-to-date layout | Measure after `skipped` is `false`, in a later frame |
Feature detection and fallback
Not every browser that supports content-visibility fires this event. Because the layout behavior of content-visibility degrades gracefully, you can treat the event as an enhancement. Check for the event handler property before you depend on it.
const supportsStateEvent =
'oncontentvisibilityautostatechange' in HTMLElement.prototype;
document.querySelectorAll('.panel').forEach((panel) => {
if (supportsStateEvent) {
panel.addEventListener('contentvisibilityautostatechange', (event) => {
panel.classList.toggle('is-active', !event.skipped);
});
} else {
// Fallback: treat every panel as active.
panel.classList.add('is-active');
}
});The fallback keeps your page correct, only less efficient. Never let the page depend on the event for correctness.
Common errors
- Using it with
content-visibility: hidden. The event never fires, because the state does not change on its own. Toggle your own class when you change the property. - Listening on the wrong element. Attach the listener to the element that has
content-visibility: auto, not to a descendant. - Starting work twice. Keep a handle, like
stopabove, so repeatedskipped: falseevents do not stack loops. - Heavy synchronous work in the handler. The handler runs in the rendering update. A long task here delays the frame that is trying to show the content.
- Treating
skipped: trueas "scrolled away". Contents with focus or a selection stay rendered even when off-screen, so the event follows relevance, not just scroll position.
Exercise
A section has content-visibility: auto and contains a setInterval that updates a clock every second. You add a contentvisibilityautostatechange listener. What should the handler do when event.skipped is true, and what must it do when event.skipped is false?
Show answer
When skipped is true, call clearInterval so the timer stops doing work for contents nobody can see. When skipped is false, start the interval again, but only if one is not already running (store the interval id and check it), and update the clock once immediately so it does not show a stale time.