NET311.tut Intersection Observer
NET311.tut Intersection Observer
files here!
All the files you need for this
tutorial can be found at
https://codepen.io/eman_
garcia/pen/ZjyORp/
A B O U T T HE A U T H O R
EMMANUEL
G ARCIA
w: wearefine.com
t: @emmanuel_garcia
job: Senior front-end
developer at FINE
areas of expertise:
HTML, SASS, JavaScript
ANIMATE ENERGETIC
SCROLLING TRANSITIONS
Emmanuel Garcia walks you through the process of using the
IntersectionObserver API to execute on-scroll animations and transitions
92 october 2018
Intersection Observer API
function when an As you can see, this setup is pretty simple. One
To observe multiple elements, you can use the same @import url(‘https://fonts.googleapis.com/css?family=N
IntersectionObserver but you’ll have to iterate through anum+Gothic+Coding’);
all of them and separately observe each element. :root {
--color-text: #fff;
const sections = document.querySelectorAll(‘.section’); --color-bg: #ddd;
sections.forEach(section => { --font-text: ‘Nanum Gothic Coding’, monospace;
observer.observe(section); --fontsize-text: 8vw;
}); }
october 2018 93
PROJECTS Intersection Observer API
@keyframes fadeInUp{
0% {
transform: translate3d(0,55%,0);
94 october 2018
Intersection Observer API
opacity:0;
transform:translate3d(0,55%,0)
} to {
transform: translateZ(0);
opacity:1;
transform:translateZ(0)
}
}
JAVASCRIPT SETUP
For the final touch, we use the IntersectionObserver
API outlined previously to detect when each section
scrolls into view. We also set the threshold value to Below Now supported
0.5 so that observer will fire when 50 per cent of the in Chrome, Firefox, Edge
and Android browsers.
element intersects with the viewport. can determine when an element enters the ‘capture For full support, there is
frame’ and then run our intersectionHandler function. a great polyfill available
(https://github.com/w3c/
const sections = document.querySelectorAll(‘.section’);
IntersectionObserver)
let config = { function intersectionHandler(entry) {
rootMargin: ‘0px’, const current = document.querySelector(‘.section.active’);
threshold: 0.5 const next = entry.target;
const header = next.querySelector(“.section--header”);
if (current) {
“There are quite a few current.classList.remove(‘active’);
deferred loading” }
}
october 2018 95