If you paid attention to some well-designed sites, youβll notice that, if they fade in an element, theyβll always fade in that element when you scroll down.
Hereβs an example where Apple fades in a block of text.
We can create this effect easily with Intersection Observer.
Making an element fade in again
If we want an element fade in again, we need to remove the is-visible class when the element goes outside of the screen.
We know the element is outside of the screen if entry.isIntersecting is false.
function callback(entries) { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add('is-visible') } else { // Element is outside the screen. entry.target.classList.remove('is-visible') } })}Only fade in elements when scrolling down
Try scrolling upwards now. Youβll notice elements above the viewport fade in as well. This happens because we removed is-visible for all elements that are outside of the viewport (which includes the ones at the top).
This is undesirable.
When you scroll past an element on a website, you expect that element to be visible. If we add fade elements in from the top, weβre going against this expectation.
On the other hand, you donβt expect elements below your viewport to be visible until they appear. We can always fade elements in from the bottom to create delight.
This means we want to remove is-visible only if the element becomes invisible by going below the viewport.
Fortunately, this is easy.
We can use boundingClientRect to tell the location of the observed element. If the top value from boundingClientRect is negative, we know the element is above the viewport.
This means we know the element went below the viewport if:
entry.isIntersectingisfalseentry.boundingClientRect.topis larger than0.
function callback(entries) { entries.forEach(entry => { if (entry.isIntersecting) { entry.target.classList.add('is-visible') }
if (!entry.isIntersecting && entry.boundingClientRect.top > 0) { entry.target.classList.remove('is-visible') } })}Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson