Daniel Daniel - 5 months ago 89
jQuery Question

How to animate Twitter Bootstrap Progress bar with jQuery

I was trying to animate with jQuery. But when I scroll back and forth, it keeps animating, and I want the width to be

width: 50%
but it keeps incrementing the width.

JS Fiddle : http://jsfiddle.net/pPf7N/310/



var target = $('.target').offset().top + 1;

$(document).scroll(function(){
if($(this).scrollTop() > target ){
$('.progress-bar').animate({
'width': '50%'
});
}
});

.progress {
margin-top: 600px;
}
.target {
height: 1000px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/js/bootstrap.min.js"></script>

<div class="target">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">60% Complete</span>
</div>
</div>
</div>




Answer

Please try this:

var target = $('.target').offset().top + 1;

var animateProgressBar = (function() {
    var animated = false;
    return function () {
        if (!animated) {
            animated = true;
           $('.progress-bar').animate({
             'width':'50%'
           });
        }
    };
})();

$(document).scroll(function(){
    if( $(this).scrollTop() > target ){
        animateProgressBar();
    }
});

Demo: http://jsfiddle.net/s7egm818/