Reputation: 23
I want to animate a progress bar with js/jquery.
I have the start time like this: "2020-02-21 05:38:33" and the end time: "2020-02-21 05:41:43". I think this could maybe be calculated with the current time and the start and end time.
Upvotes: 0
Views: 1280
Reputation: 727
I created a sample progress bar with Bootstrap, jQuery & momentjs. Hope this will help you.
$(document).ready(function(){
var start = moment('2020-02-21 05:38:33');
var end = moment('2020-02-21 20:00:00');
var formattedPercentage = 0;
var interval = setInterval(function(){
var now = moment();
var percentage = now.diff(start) / end.diff(start) * 100;
if (percentage > 100) {
formattedPercentage = 100;
clearInterval(interval);
} else {
formattedPercentage = percentage.toFixed(2);
}
// Use formattedPercentage as you need
$('#example-progress-bar .progress-bar').width(formattedPercentage+'%').html(formattedPercentage+'%')
}, 500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="example-progress-bar" class="progress">
<div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Upvotes: 2