I am working on dynamically displaying an SVG item as it enters the viewport using an observer. The animation associated with the SVG item should only play when it becomes visible in the view window. Initially, I have set the display
property to none
, and created a separate class to change the property to block
. Adding this class manually through the inspector works fine. My goal is to automatically add the animation class front-social-start
to the element's class list once it comes into view.
If anyone can help out, that would be greatly appreciated - currently fueling my work solely on caffeine due to this little bug XD
HTML
<div class="radial-graph-container">
<svg width="200" height="200" class="chart-container">
<circle cx="100" cy="100" r="90" class="back" fill="none" />
<!-- The below circle is the one I want to select -->
<circle cx="100" cy="100" r="90" class="front-social" fill="none" />
<g class="graph-center-txt">
<text
x="100"
y="100"
alignment-baseline="central"
text-anchor="middle"
id="percentage-social-media-usage"
>
0%
</text>
</g>
</svg>
</div>
CSS
.back {
stroke: #101114;
stroke-width: 10;
}
.front-social {
stroke: #e96f31;
stroke-width: 15;
stroke-dasharray: 395.84;
transform: rotate(-90deg);
transform-origin: center;
animation: fill 1.7s reverse;
display: none;
}
.front-social-start {
display: block;
}
JS
const el = document.querySelector('.font-social');
const observer = new IntersectionObserver(entries => {
// Loop over the entries
entries.forEach(entry => {
// If the element is visible
if (entry.isIntersecting) {
// Add the animation class
el.classList.add('front-social-start');
}
});
});
observer.observe(document.getElementsByClassName('.front-social'));