0% found this document useful (0 votes)
25 views4 pages

NET311.tut Intersection Observer

The document provides a tutorial on using the IntersectionObserver API for implementing on-scroll animations and transitions in web development. It explains how to set up the API, configure it to observe multiple elements, and trigger animations based on their visibility in the viewport. The tutorial also highlights the performance benefits of using this API compared to traditional scroll event techniques and mentions its support in modern browsers along with a polyfill for older ones.

Uploaded by

eman.7g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views4 pages

NET311.tut Intersection Observer

The document provides a tutorial on using the IntersectionObserver API for implementing on-scroll animations and transitions in web development. It explains how to set up the API, configure it to observe multiple elements, and trigger animations based on their visibility in the viewport. The tutorial also highlights the performance benefits of using this API compared to traditional scroll event techniques and mentions its support in modern browsers along with a polyfill for older ones.

Uploaded by

eman.7g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PROJECTS Intersection Observer API View source

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

INTERSECTION OBSERVER API

ANIMATE ENERGETIC
SCROLLING TRANSITIONS
Emmanuel Garcia walks you through the process of using the
IntersectionObserver API to execute on-scroll animations and transitions

The IntersectionObserver API is a promising or transitions is the heavy reliance on resource-


and exciting new web API that tackles one of intensive scroll events to detect when an element
the most common issues for web developers: appears in the viewport. With the amount of
detecting the visibility of elements when they come complex calculations needed to solve for this,
into view. This API helps simplify the problem by you would ultimately have to lean on third-party
providing a more modern solution for detecting libraries to get the job done.
element intersections. IntersectionObserver has This is where IntersectionObserver comes in.
many use cases for implementing deferred It allows you to easily register a callback that is
functionality, including lazy loading images, as well executed when an element being observed intersects
as triggering animations and transitions. with another element or with the viewport.
According to specs, “The IntersectionObserver API In this tutorial, I will explain how to set up and
provides a way to asynchronously observe changes in configure an IntersectionObserver to observe
the intersection of a target element with an ancestor multiple elements at once, as well as watch the
element or with a top-level document’s viewport.” callbacks to trigger some nifty animations once
This modern web API allows you to observe and elements intersect with the viewport.
trigger a callback function when an element is visible
in the viewport or intersects with another element. API SETUP
Some of the previous difficulties developers To use the IntersectionObserver API you simply need
have had with implementing on-scroll animations to create an IntersectionObserver instance and pass

92 october 2018
Intersection Observer API

element(s) to the observe() function. You can also TUTORIAL SETUP


pass a config object into the Observer’s constructor to In this tutorial we’ll use the IntersectionObserver
configure with the following: API to observe multiple elements at once and
trigger various animations and transitions as each
● r oot: defines the root element used as ‘capture respective panel scrolls into view. We’ll use CodePen
frame’ for intersection checking. This defaults to for this tutorial, with a fairly straightforward HTML
the viewport but can be any element. structure. Start by creating the initial container
● r ootMargin: defines margin set around root. Supports element where we will add our section panels.
same values as CSS margins. Extends or minimises
intersection point. <div class=”container”>
● t hreshold: a value or array of values between 0 <div class=”sections”>
and 1. It corresponds to the ratio of visibility of <!-- section markup goes here -->
an element, with 0 meaning completely out of </div>
view and 1 being 100 per cent in view. </div>
IntersectionObserver is direction agnostic, so
it will be triggered when an element enters and Each section contains an img element with
leaves ‘capture frame’. In the case of multiple photography taken from a specific location, as well
values, the intersection callback is triggered when as header text containing the image location name.
each threshold value is met.
<div class=”section” data-bgcolor=”#C1A5A9”>
<h2 class=”section--header”>Kénitra, Morocco</h2>
<div class=”section--image”><img src=”https://
“This web API allows images.unsplash.com/photo-1532173311168-

you to observe and 91e999ce4e47?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyM


Dd9&s=cf6ff267733890306ca709fa2184dd3a&auto=for
trigger a callback mat&fit=crop&w=1301&q=80” /></div>

function when an As you can see, this setup is pretty simple. One

element is visible” thing to note is that we use a custom data attribute


called data-bgcolor for each panel in order to animate
the body background colour as each section scrolls
Here is a quick sample of what that code would into view. We then pull in the data attribute to our
look like: IntersectionObserver callback function in order to
execute this functionality.
let config = {
root: null, // avoiding ‘root’ or setting it to ‘null’ sets it to SASS + CSS VARIABLES
default value: viewport We use SASS (SCSS) as a preprocessor for this
rootMargin: ‘0px’, // margin around root. Values are tutorial. You can easily set this in CodePen settings.
similar to CSS property. Values without units not allowed Also, we’ll add some CSS custom property variables
threshold: 0.5 // visible amount of item shown in relation to set some default styles, which can easily be
to root. Can also be an array [0, .25, .5, 1] reused throughout our SASS code.
}; CSS variables are pretty nifty as they are
let observer = new IntersectionObserver((entries) => { somewhat similar to SASS variables but you can also
… pull in these custom property values into JavaScript
}, config); and update accordingly. I have also imported a
observer.observe(element); Google font for this specific tutorial.

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

BODY STYLES opacity: 0;


Here we use some of our CSS variables to set some transition: opacity .3s;
global styles for text colour and background colour. .active & {
We also add a CSS transition to the body element in opacity: 1;
order to animate and ease in the background colour }
when it switches on scroll. img {
display: block;
body { position: relative;
min-height: 100vh; max-width: 90%;
color: #000; margin: 0 0 0 auto;
color: var(--color-text); }
background-color: #fff; }
background: var(--color-bg);
-webkit-font-smoothing: antialiased; SECTION TEXT
-moz-osx-font-smoothing: grayscale; The section location header has a couple of CSS
transition: background .3s; variables in use for font-size and font-family. These
} can easily be changed by updating the global CSS
variables we created earlier. The text is set to position:
SECTIONS fixed in order to keep the element in the same
Each section div uses vh units to take up 100 per cent position in the viewport as you scroll.
of the minimum height of the viewport. This is an We also apply some relative length units for
easy way to make sure each panel has enough room padding and bottom properties. Vmax units translate
to scroll through and allow images to display with its to a percentage of the width or height of the
natural height. viewport, whichever is the larger dimension. For the
animation, we use a sequence with keyframes to fade
.section { in the text and slide up at the same time.
position: relative;
min-height: 100vh; .section--header {
} font-size: calc(var(--fontsize-text));
font-family: var(--font-text);
SECTION IMAGES position: fixed;
For the images, we align them to the right of each bottom: 5vmax;
section and set them to opacity: 0. We also set a CSS left: 0;
transition for opacity so as to fade in/out the image padding-left: 5vmax;
as it scrolls into view using IntersectionObserver. z-index: 1000;
line-height: 1;
.section--image { font-weight: 300;
display: block; opacity: 0;
Below Example of the
bounding rectangles
position: relative; animation-duration: .65s;
calculated by max-width: 100%; animation-fill-mode: both;
IntersectionObserverEntry.
These calculations
margin: 10vh 0 30vh auto; .active & {
help to determine the animation-name: fadeInUp;
isIntersecting property.
}
}

The CSS animation is pretty straightforward as you


are setting the opacity to 0 and using the transform
property to move the element down to start. Once
the animation sequence finishes, it will set opacity to
1 and reset transform to 0. This in turn creates a fluid
CSS animation that takes .65s to complete.

@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’);

other use cases worth }


if (next) {
diving into, including next.classList.add(‘active’);
document.body.style.setProperty(“--color-bg”, next.
lazy loading, as well as dataset.bgcolor);

deferred loading” }
}

}; Within our handler function we are setting an active


let observer = new IntersectionObserver((entries) => { class to each current section that comes into view,
entries.forEach(entry => { which in turn activates our CSS animations and
if (entry.isIntersecting) { transitions that we declared earlier. By accessing
intersectionHandler(entry); and updating CSS variables in a clean and concise
} manner, we’re also updating body background
}); colour, which creates a simple but effective
}, config); transition effect on the front end.
sections.forEach(section => {
observer.observe(section); SUMMARY
}); The IntersectionObserver API is a straightforward
tool for detecting element intersections in the
By creating our IntersectionObserver instance we viewport and has many performance benefits
are able to access these entries through the callback compared to older techniques relying on scroll
function. This array of observed entry types are events. There are also quite a few other use cases
known as IntersectionObserverEntry. that are worth diving into, including lazy loading of
Through this interface we are provided with images, as well as deferred loading to allow you to
three different rectangles that help determine run certain functionality only when it’s in view.
an element’s positioning and boundaries. This IntersectionObserver also has decent support in
information is calculated asynchronously – a modern browsers (https://caniuse.com/#search=Intersec
big boost for performance as we no longer have tionObserver) and there is a great polyfill available
to calculate these types of values ourselves. The for other browsers that don’t fully support it yet.
IntersectionObserverEntry interface also provides us with (https://github.com/w3c/IntersectionObserver/tree/
a handy property called isIntersecting. With this, we master/polyfill).

october 2018 95

You might also like