Animate width of a progressbar

Viewed 197

I want to animate five bootstrap progressbars to a specific width. So I defined the specific width in the @keyframes five times. Is there a way to do it with just one animation? Also because I want to animated it only when it is in viewport and used an intersectionObserver, which is not working with five classes I think...

Progress bar:

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    const progressbar = entry.target.querySelector('.progressbar');

    if (entry.isIntersecting) {
      progressbar.classList.add('bar1');
    return; 
    }

    
    progressbar.classList.remove('bar1');
  });
});

observer.observe(document.querySelector('.progress'));
.bar1 {
  animation: bar1 3s ease-in-out;
  animation-fill-mode:both;
}
@keyframes bar1  {
  0% { width: 0; }
  100% { width: 60%; }
}
<div class="col-sm-6">
  <h3 class="progress-title">SEO / SEM</h3>
  <div class="progress">
    <div class="progress-bar bar1">
      <div class=" progress-value">60%</div>
   </div>

1 Answers

You could try manually setting the style.width property in the progressbar with JS, and instead of it having an animation, instead apply a transition.

.bar1 {
  transition: width 3s ease-in-out;
}

Then

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    const progressbar = entry.target.querySelector('.progressbar');

    if (entry.isIntersecting) {
      progressbar.style.width = someTargetWidth;
    return; 
    }

    progressbar.style.width = someInitialWidth;
  });
});

observer.observe(document.querySelector('.progress'));
Related