skip to Main Content

HTML:

<div class="container">
           <div class="progress-bar"></div>
 </div>

CSS:

.container {
    height: 10px;
    width: 30%;
    background-color: lightgrey;
    position: relative;
    border-radius: 3px;
    top: 35%;
    left: 15%; 
  }

  .container .progress-bar {
    position: absolute;
    height: 100%;
    border-radius: 3px;

    background-color: #393939;
    animation: progress-animation 5s forwards;
    
  }

  @keyframes progress-animation {
    0% { width: 0%;}
    85% { width: 85%;}

How do I make it so the animation doesn’t return back to zero after fully animating. But stay at the percentage it animated too (In this case 85%)? if that makes sense. Basically whenever I reload the page I want the progress bar to animate to 85% and remain like that, only resetting when i reload the page again.

2

Answers


  1. Keeping all your HTML/CSS code as it is (plus a missing curly brace at the end), I would just add a controller component in JS, to get the desired behaviour:

    document.addEventListener("DOMContentLoaded", function() {
        const progressBar = document.querySelector(".progress-bar");
        const animationDuration = 5; // Animation duration in seconds
        const progress = 85; // Desired progress in percentage
    
        progressBar.style.animationDuration = `${animationDuration}s`;
        progressBar.style.width = `${progress}%`;
    });
    

    I just added that JS block above in your Codepen (in place of the empty JS section) and I think it now does what you need.

    Login or Signup to reply.
  2.   0% { width: 0%;}
      85% { width: 85%;}
    

    That should be:

        0% { width: 0%;}
        100% { width: 85%;}
    

    No need for javascript

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search