Home > database >  Simple CSS animation to run for all elements
Simple CSS animation to run for all elements

Time:10-16

Currently, my animation only works for the first element (a progress bar). I want my animation to run for all of those.

Below is the HTML code to run through several progress bars and JS code to fill the progress bar upon scrolling

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    const square = entry.target.querySelector('.progress-bar');

    if (entry.isIntersecting) {
      square.classList.add('progress-animation');
      return; // if we added the class, exit the function
    }

    // We're not intersecting, so remove the class!
    square.classList.remove('progress-animation');
  });
});

observer.observe(document.querySelector('.progress'));
@media (prefers-reduced-motion: no-preference) {
  .progress-animation {
    animation: 2s linear 0s normal none infinite running progress-bar-stripes, animate-positive 3s;
    -webkit-animation: 2s linear 0s normal none infinite running progress-bar-stripes, animate-positive 3s;
  }
}
<h5>Excel</h5>
<div >
  <div  role="progressbar" aria-label="Basic example" style="width: 95%;" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100">
  </div>
</div>
<h5>PowerBI</h5>
<div >
  <div  role="progressbar" aria-label="Basic example" style="width: 85%;" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100">
  </div>
</div>

CodePudding user response:

It works like that because you use document.querySelector('.progress') but to find all elements with that class you should use document.querySelectorAll('.progress'). Like that.

document.querySelectorAll('.progress').forEach(el => observer.observe(el));
  • Related