Intersection observer - test
by jonahe
HTML
<main>
<section>
<article>
1
</article>
<article>
2
</article>
<article>
3
</article>
<article>
4
</article>
<article>
5
</article>
<article>
6
</article>
</section>
</main>
CSS
body {
max-height: 100vh;
overflow: scroll;
}
section {
background: teal;
padding: 10px;
}
article {
display: flex;
justify-content: center;
align-items: center;
border: 1px solid tomato;
height: 40vh;
background-color: indigo;
color: black;
font-size: 40px;
font-weight: bold;
transition: all 2s 0s ease-in;
}
article.high-visiblity {
background-color: yellow;
color: tomato;
}
JavaScript
const options = {
//root: document.querySelector('body'),
rootMargin: '0px',
threshold: [0.4,0.8]
}
const callback = (entries, observer) => {
entries.forEach(entry => {
if(entry.intersectionRatio > 0.8) {
entry.target.classList.add("high-visiblity");
entry.target.innerHTML = entry.target.innerHTML[0] + " in";
} else {
entry.target.classList.remove("high-visiblity");
entry.target.innerHTML = entry.target.innerHTML[0] + " out";
}
})
};
const observer = new IntersectionObserver(callback, options);
const articles = Array.from(document.querySelectorAll("article"));
articles.forEach(article => observer.observe(article));