JSFiddle - React, Tailwind, and code Playground
by Hemanth HM
HTML
<div id="container" style="">
<div id="msgBox">
The element we are observering is in viewport
</div>
<div id="track">
I shall scroll out of view-port
</div>
</div>
CSS
body{
text-align: center;
font-family: 'Averia serif libre';
background-color: crimson;
color: aliceblue;
height: 200vh;
}
#msgBox {
justify-content: center;
align-items: center;
display: flex;
position: fixed;
left: 0;
right: 0;
bottom: 0;
}
JavaScript
const msgBox = document.querySelector('#msgBox');
const callback = (entries, observer) => {
if(entries[0].isIntersecting) {
msgBox.innerHTML = `The element we are observering is in viewport 👍`;
} else {
msgBox.innerHTML = `The element we are observering is not in viewport 👎`;
}
};
if (!!window.IntersectionObserver) {
const observer = new IntersectionObserver(callback);
observer.observe(document.querySelector('#track'))
}