How To Create Content Animated When Scrolling Down
A trivial bit of animation on a site tin can add some flair, impress users, and get their attention. You could accept them run, no thing where they are on the folio, immediately when the folio loads. But what if your website is fairly long and so information technology took some fourth dimension for the user to scroll down to that element? They might miss it.
Yous could have them run all the time, only perhaps the animation is all-time designed so that y'all for sure see the first of information technology. The play a trick on is to start the animation when the user scrolls down to that chemical element — scroll-triggered blitheness, if you will.
To tackle this we use gyre triggers. When the user scrolls down to any particular element, we can use that event to practice something. It could be annihilation, even the beginning of an blitheness. Information technology could even be curlicue-triggered lazy loading on images or lazy loading a whole comments department. In that way, we won't strength users to download elements that aren't in the viewport on initial folio load. Many users may never scroll down at all, so we actually save them (and united states of america) bandwidth and load fourth dimension.
Roll triggers are very useful. There are many libraries out there that you lot can employ to implement them, like Greensock'southward pop ScrollTrigger plugin. But you don't have to use a third-party library, particularly for adequately uncomplicated ideas. In fact, you tin implement information technology yourself using just a small handful of vanilla JavaScript. That is what we are going to practice in this article.
Here'south how nosotros'll make our roll-triggered event
- Create a function chosen
scrollTrigger
we can employ to certain elements - Apply an
.active
form on an element when it enters the viewport - Animate that .
agile
class with CSS
There are times where adding a .active
class is not plenty. For example, we might want to execute a custom function instead. That ways we should be able to pass a custom function that executes when the element is visible. Like this:
scrollTrigger('.loader', { cb: function(el) { el.innerText = 'Loading ...' loadContent() } })
Nosotros'll as well attempt to handle scroll triggers for older non-supporting browsers.
Just first, the IntersectionObserver
API
The main JavaScript feature nosotros're going to apply is the Intersection Observer. This API provides a style to asynchronously find changes in the intersection of a target element — and information technology does so more in a more than performant way than watching for scroll
events. We volition use IntersectionObserver
to monitor when scrolling reaches the point where sure elements are visible on the page.
Permit's start edifice the scroll trigger
Nosotros desire to create a function called scrollTrigger
and this part should take a selector as its argument.
role scrollTrigger(selector) { // Multiple element tin have same class/selector, // then we are using querySelectorAll let els = document.querySelectorAll(selector) // The to a higher place `querySelectorAll` returns a nodeList, // and so we are converting it to an array els = Array.from(els) // Now we are iterating over the elements array els.forEach(el => { // `addObserver part` will attach the IntersectionObserver to the element // Nosotros volition create this function next addObserver(el) }) } // Example usage scrollTrigger('.roll-reveal')
Now let's create the addObserver
function that want to adhere to the element using IntersectionObserver
:
role scrollTrigger(selector){ let els = certificate.querySelectorAll(selector) els = Array.from(els) els.forEach(el => { addObserver(el) }) } function addObserver(el){ // We are creating a new IntersectionObserver instance permit observer = new IntersectionObserver((entries, observer) => { // This takes a callback function that receives two arguments: the elements list and the observer example. entries.forEach(entry => { // `entry.isIntersecting` will be true if the element is visible if(entry.isIntersecting) { entry.target.classList.add('agile') // We are removing the observer from the element afterwards adding the active class observer.unobserve(entry.target) } }) }) // Adding the observer to the element observer.observe(el) } // Example usage scrollTrigger('.scroll-reveal')
If we do this and scroll to an element with a .scroll-reveal
course, an .active
class is added to that element. But notice that the active
class is added as soon as any small part of the element is visible.
Just that might exist overkill. Instead, we might desire the .active
class to be added once a bigger part of the chemical element is visible. Well, thankfully, IntersectionObserver
accepts some options for that as its second argument. Let's apply those to our scrollTrigger
function:
// Receiving options as an object // If the user doesn't pass any options, the default will be `{}` part scrollTrigger(selector, options = {}) { let els = document.querySelectorAll(selector) els = Array.from(els) els.forEach(el => { // Passing the options object to the addObserver role addObserver(el, options) }) } // Receiving options passed from the scrollTrigger office function addObserver(el, options) { let observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if(entry.isIntersecting) { entry.target.classList.add('agile') observer.unobserve(entry.target) } }) }, options) // Passing the options object to the observer observer.observe(el) } // Example usage 1: // scrollTrigger('.coil-reveal') // Example usage 2: scrollTrigger('.scroll-reveal', { rootMargin: '-200px' })
And just similar that, our first two calendar items are fulfilled!
Let'south motility on to the third item — adding the ability to execute a callback function when nosotros gyre to a targeted element. Specifically, let'southward pass the callback function in our options object every bit cb
:
function scrollTrigger(selector, options = {}) { permit els = certificate.querySelectorAll(selector) els = Array.from(els) els.forEach(el => { addObserver(el, options) }) } role addObserver(el, options){ let observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if(entry.isIntersecting){ if(options.cb) { // If we've passed a callback role, we'll call it options.cb(el) } else{ // If nosotros haven't, nosotros'll merely add the active class entry.target.classList.add('active') } observer.unobserve(entry.target) } }) }, options) observer.find(el) } // Example usage: scrollTrigger('.loader', { rootMargin: '-200px', cb: function(el){ el.innerText = 'Loading...' // Washed loading setTimeout(() => { el.innerText = 'Task Consummate!' }, 1000) } })
Not bad! At that place's i concluding affair that we need to take intendance of: legacy browser support. Sure browsers might lack support for IntersectionObserver
, and then let's handle that instance in our addObserver
function:
office scrollTrigger(selector, options = {}) { let els = certificate.querySelectorAll(selector) els = Array.from(els) els.forEach(el => { addObserver(el, options) }) } function addObserver(el, options) { // Check if `IntersectionObserver` is supported if(!('IntersectionObserver' in window)) { // Uncomplicated fallback // The blitheness/callback volition be called immediately so // the roll animation doesn't happen on unsupported browsers if(options.cb){ options.cb(el) } else{ entry.target.classList.add('active') } // We don't need to execute the rest of the code return } let observer = new IntersectionObserver((entries, observer) =>; { entries.forEach(entry => { if(entry.isIntersecting) { if(options.cb) { options.cb(el) } else{ entry.target.classList.add together('active') } observer.unobserve(entry.target) } }) }, options) observer.observe(el) } // Example usages: scrollTrigger('.intro-text') scrollTrigger('.whorl-reveal', { rootMargin: '-200px', }) scrollTrigger('.loader', { rootMargin: '-200px', cb: role(el){ el.innerText = 'Loading...' setTimeout(() => { el.innerText = 'Job Complete!' }, 1000) } })
Here'south that alive demo over again:
And that's all for this little journey! I hope y'all enjoyed it and learned something new in the procedure.
Source: https://css-tricks.com/scroll-triggered-animation-vanilla-javascript/
Posted by: warnerhipt1970.blogspot.com
0 Response to "How To Create Content Animated When Scrolling Down"
Post a Comment