JSFiddle - React, Tailwind, and code Playground
Intersection Observer test with animated interior elements
by Travis Almand
HTML
<div id="container">
<div id="contained"><div></div></div>
</div>
<div id="panel">
<div id="intersecting">isIntersecting: <span></span></div>
<div id="ratio">intersection ratio: <span></span></div>
</div>
SCSS
body {
align-items: center;
background-color: #E0E0E0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
justify-content: center;
}
#container {
align-items: center;
background-color: #fff;
border: 3px solid rebeccapurple;
display: flex;
height: 400px;
justify-content: center;
width: 400px;
}
#contained {
align-items: center;
background-color: rebeccapurple;
display: flex;
height: 200px;
justify-content: center;
transform: translate3d(-350px, 0, 0);
width: 200px;
&::before {
animation: sidetoside 3s linear infinite alternate;
background-color: red;
content: '';
display: block;
height: 50px;
position: absolute;
width: 50px;
}
div {
animation: sidetoside 3s 3s linear infinite alternate;
background-color: green;
display: block;
height: 50px;
position: absolute;
width: 50px;
}
}
#panel {
margin: 10px;
width: 400px;
}
@keyframes sidetoside {
0% {
transform: translate3d(0 0, 0);
}
100% {
transform: translate3d(350px, 0, 0);
}
}
JavaScript
console.clear();
let sliderH = document.querySelector('#horizontal');
let container = document.querySelector('#container');
let contained = document.querySelector('#contained');
let isIntersecting = document.querySelector('#intersecting span');
let intersectionRatio = document.querySelector('#ratio span');
let options = {
root: container,
rootMargin: '0px',
threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
}
let observer = new IntersectionObserver(callback, options);
observer.observe(contained);
function callback (entries, observer) {
entries.forEach(entry => {
isIntersecting.innerText = entry.isIntersecting;
intersectionRatio.innerText = entry.intersectionRatio;
})
}