intersectionRatio is an IntersectionObserver entry property that reports how much of a target element is visible inside the intersection root. A value of 0.0 means fully hidden; 1.0 means fully visible. section 13.3.2 section 13.4
Treat the ratio as a normalized value between 0 and 1, then map it directly to visual properties. For example, opacity can equal the ratio, scale can use 0.8 + (ratio × 0.2), and vertical movement can use (1 − ratio) × 30 pixels. section 13.3.2
A scroll animation can use the ratio to control:
- Opacity from 0 when the card is offscreen to 1 when fully visible. section 13.3.2
- Scale from 0.8 to 1.0 as visibility increases. section 13.3.2
- translateY from 30 pixels down to 0 pixels as the card enters the viewport. section 13.3.2
Progressive portfolio-card animation
Observe portfolio cards with thresholds from 0 through 1 in 0.01 increments. On each visibility update, read entry.intersectionRatio and assign the resulting opacity and transform values to the target element. section 13.3.2 section 13.4
Listing 13.7 Making UI changes with an intersection observer
function setupScrollAnimations() {
const options = { # #1
root: null,
rootMargin: '0px',
threshold: Array.from({ length: 101 }, (_, i) => i / 100)
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const element = entry.target;
const ratio = entry.intersectionRatio; #2
const opacity = ratio; #3
const scale = 0.8 + (ratio * 0.2); #4
const translateY = (1 - ratio) * 30; #5
element.style.opacity = opacity; #6
element.style.transform = ` #6
translateY(${translateY}px) #6
scale(${scale}) #6
`; #6
});
}, options);
document.querySelectorAll('.scroll-animate') #7
.forEach(element => { #7
observer.observe(element); #7
}); #7
} #7
setupScrollAnimations();
Inspect the complete JavaScript implementation, including observer options, threshold creation, ratio-based calculations, and CSS updates. section 13.3.2
