mikemaccana
mikemaccana

Reputation: 123148

How can I end a CSS animation early?

I am using CSS animation to make a progress bar.

Here's a working JSfiddle

Since this is a progress bar for searching, sometimes the search will take less than the animation time - at which point I want the animation to end. I've added a timeout to the JSFiddle.

However a timeout to add a class to make the progress-bar 100% width (the final state of the animation) doesn't work. The browser still displays the progress bar as whatever width the animation uses until the animation is complete.

How can I end a CSS animation early, using JavaScript?

Upvotes: 1

Views: 81

Answers (2)

James Thorpe
James Thorpe

Reputation: 32202

You can shift the completed class outside of searching, so the animation no longer applies, then simply remove the searching class:

SCSS:

.progress-bar {
  width: 300px;
  height: 20px;
  background-color: #222;
  .completion {
    width: 0%;
    height: 20px;
    background-color: green;
    &.searching {
      animation-duration: 60s;
      animation-name: show-progress;
      animation-fill-mode: forwards;
    }
    &.completed {
      width: 100%;
    }
  }
}

JS:

setTimeout(function(){
  progress.classList.remove('searching')
  progress.classList.add('completed') 
  console.log('Added completed')
}, 1*1000)

Here's an updated fiddle.

Upvotes: 1

Dekel
Dekel

Reputation: 62556

You can change the animation-duration of the progress:

  &.completed {
    width: 100%;
    animation-duration: 3s;
  }

Here is the working example:
https://jsfiddle.net/kmer8s5c/2/

Upvotes: 1

Related Questions