Intersection Observer API: How to have each circular progress bar fill when they are in viewport?
Sorry if the formatting is horrible. My first time asking a question! I am creating a stat module for the user to input a value and that value will get taken into a circular progress bar that fills up when the progress bar is in the viewport. I have it working partially BUT I am now stuck. When I have 3 x 2 lay out. All the stats will fill up twice. Once when the first row is in the viewport and another time when second row is in the viewport. Another issue I am running into is when the stats are stacked on mobile - once the first stat is in the viewport it fires for all the stats to fill up at the same time. I would like for the stat bar to fill up as each stat comes into view for mobile and once each time on desktop/tablet. What am I missing here? I can share code as well. Thank you!
28 Replies
You are probably observing the container that holds all the stats instead of observing the container/element for individual stats.
I think they are observing them individually but updating them all at once.
@rnkwill could you provide a minimal reproduction of your issue in a codepen
https://codepen.io/rnkwill/pen/OJrzroj
First time using codepen to post something so let me know if that link works.
restarting animations is actually hell
Tell me about it. I've been at this for 3 days now and it's my first time really trying somethihng like this 😦
im trying to understand what exactly you want to do
so, basically, you want to animate it going from 0 to some %?
and when you scroll away, you want to restart it?
No. I have the animation going from 0 to whatever value the user inputs. What I am trying to do is have the animation fire whenever each circular stat is in the viewport. At the moment it does that BUT once the second div is intersecting ALL 6 of the stat modules will animate again instead of just the second row.
Additionally when I have them stacked in a single column whenever the first stat is intersecting - all of the stats fire when I want each to fire once they are in viewport
Let me know if that makes sense
Ok i see
easy
you're not handling the target on the intersection entry
you're handling all 6 entries at once
your mistake starts on line 15
So basically, you just have to remove the for loop that is in your observer callback and use the entry object it is giving you to choose which element to start the animation on
correction: the entry target
you literally just remove the for loop
Yes
let container = statContainer[i];
replaced by let container = entry.target;
and it should work
it's literally what i did and it worksWOW! Thanks for the assist!
Also another question.. when I change the value in the HTML to a decimal such as 99.9
(and please rename the parameter of the forEach loop at the bottom, you are shadowing the main
statContainer
and it makes the code hard to read)