ScrollObserver A lightweight⚡(less than 1KB) JavaScript library to animate easily elements on scroll into view.
When a DOM element is onscreen it adds shown class to it and when offscreen removes that shown class.
scrollObserver('.card')The above JavaScript code adds and removes the shown class to the elements which have card class (select elements like querySelectorAll()) when they are onscreen and offscreen respectively.
You can pass multiple selectors as an array of string.
scrollObserver(['.card','.box'])Write css of .card and .card.shown like this
.card{
...
...
transition: 400ms;
opacity : 0;
}
.card.shown {
opacity:1;
}constoptions={root : document.querySelector('.container'),rootMargin : '10px',threshold: [0,0.25,0.5,0.75,1],once: true,onshow: function(entry){console.log("Showing ")},onhide: function(entry){console.log("Hiding ")},}scrollObserver('.card',options)Read more about Options argument from MDN Docs
If the value of once is true, it will work once.
They are callback functions. They are called when the element becomes onscreen or offscreen
Read them from MDN Docs
- index.html
- style.css
- script.js
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible" content="IE=edge"><metaname="viewport" content="width=device-width, initial-scale=1.0"><title>Scroll Observer</title><scriptsrc="./script.js" type="module" defer></script><linkrel="stylesheet" href="style.css"></head><body><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div><divclass="card"><h1>Scroll Observer</h1></div></body></html>*{
font-family: Arial, Helvetica, sans-serif;
}
.card{
width:min(90%,500px);
aspect-ratio:2/1;
margin-inline: auto;
background-color:hsl(61,70%,70%);
display: grid;
place-items: center;
margin-block:7%;
border-radius:10px;
transition:400ms;
opacity:0;
scale:0.8;
}
.card.shown {
opacity:1;
scale:1;
}importscrollObserverfrom'https://codeabinash.github.io/scroll-observer/index.min.js'scrollObserver('.card')