Search code examples
jqueryflipclock

Add progress bar to countdown


I'm working on a simple countdown using flipclockjs. What I'm trying to do is add a progress bar that is sync to the countdown. I tried to do it, but I can't even get the number of seconds.

Hope you help me.

var clock = $('.my-clock').FlipClock(10, {
  countdown: true,
  callbacks: {
    stop: function() {    
      setTimeout(function(){
        clock.setTime(10); // proceeding time
        clock.start();
      },1000);
    }
  }
});
.my-clock {
  text-align:center;
  width:auto;
  display: inline-block;
}
.center {
  text-align:center;
  
}
.progressBar{
  margin: 0 auto;
  width: 400px;
  height: 6px;
  border-radius: 3px;
  background-color: #222;
}
.progress{
  background-color: green;
  height: 100%;
  width: 30%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.min.js"></script>

<div class="center">
  <div class="my-clock"></div>
  <div class="progressBar">
    <div class="progress"></div>
  </div>  
</div>


Solution

  • Well if you refer to the documentation of FlipClock, the interval callback is called on each interval, and I did some dom manipulations to update the progressbar.

    let time = 20;
    let progress = 0; let counter = 0
    var clock = $('.my-clock').FlipClock(time, {
      countdown: true,
      count: 1,
      callbacks: {
        stop: function() {
          setTimeout(function(){
            clock.setTime(time); // proceeding time
            clock.start();
          },1000);
        },
        interval: function() {
          counter && (progress+=100/time);
          counter ++;
          $('.progressBar .progress').width(progress+ '%');
          if(progress >= 100) {
            progress = 0; counter = 0;
            this.stop()
          }
        }
      }
    });
    .my-clock {
      text-align:center;
      width:auto;
      display: inline-block;
    }
    .center {
      text-align:center;
      
    }
    .progressBar{
      margin: 0 auto;
      width: 400px;
      height: 6px;
      border-radius: 3px;
      background-color: #222;
    }
    .progress{
      background-color: green;
      height: 100%;
      width: 100%;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.min.js"></script>
    
    <div class="center">
      <div class="my-clock"></div>
      <div class="progressBar">
        <div class="progress"></div>
      </div>  
    </div>