Reputation: 2084
I am designing an animated progress bar with jQuery / Bootstrap. My progress bar has 8 'steps', each one representing 12.5% of the width of the entire progress bar.
I've designed a function that works well when animating bar changes from steps one through four. However, when step five comes along, for some reason the bar animates to 100% before going back down to 50%. The same thing happens at steps 6, 7, and 8.
Is there something I'm doing wrong here? Why is my animate() function jumping the width of the bar to 100% at step 5 before toning it back down to 62.5%?
javascript
window.total = 0;
window.target = 8;
var progress_percent_full = window.total / window.target;
function update_progress_bar() {
progress_percent_full = (window.total / window.target) * 100;
new_width = progress_percent_full + "%";
$("#progress-bar").animate({
width: new_width,
});
$("#progress-bar").text(total);
}
$("#button").click(function() {
window.total = window.total + 1;
update_progress_bar();
});
html
<button class="btn btn-lg btn-primary" id="button">
Change bar
</button>
<div style="position: fixed; bottom: 0px; left: 0px; right: 0px; height: 75px; background: #dedede;">
<div class="progress" style="max-width: 500px; margin: 0 auto; position: relative; top: 30px;">
<div class="progress-bar" id="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="8"></div>
</div>
</div>
JSFiddle example showing what's going on (hit the button 5-6 times)
Upvotes: 1
Views: 918
Reputation: 8126
Apparently the .animate()
method is not that reliable when used with percentages. As an alternative, you could use pixel values like so:
function update_progress_bar() {
var progress = (window.total / window.target),
new_width = $("#progress-bar").parent().width() * progress;
$("#progress-bar").animate({
width: new_width,
}).text(window.total);
}
Alternatively you could drop the .animate() method, and handle the animation with css. You can do that like this:
<style>
.progress-bar {
transition: width 1s;
}
<style>
function update_progress_bar() {
progress_percent_full = (window.total / window.target) * 100;
var new_width = progress_percent_full + "%";
$("#progress-bar").width(new_width).text(total);
}
Upvotes: 2