Dryden Long Dryden Long - 2 months ago 25
CSS Question

Unwanted Delay in jQuery Animate

I have a function that animates the width of a div to simulate a progress bar as the user types in form information. When the information is typed in faster than the animation, it pauses in between animations and then starts again, making the animation choppy.

How can I make the animation smoother when the user finishes typing in the next form field prior to the previous field's animation being completed?

HTML

<div id="container">
<div class="stepProgress">
<div id="currentProgress"></div>
</div>
<div class="formContainer">
<input id="firstName" type="text" class="k-textbox progInput" placeholder="First Name" />
<input id="lastName" type="text" class="k-textbox progInput" placeholder="Last Name" />
<input id="userName" type="text" class="k-textbox progInput" placeholder="User Name" />
<input id="userEmail" type="text" class="k-textbox progInput" placeholder="Email" />
</div>
</div>


CSS

.stepProgress {
height: 10px;
width: 100%;
}

#currentProgress {
width: 0px;
height: 100%;
background-color: #00BFF2;
}
#container {
width: 500px;
height: 300px;
border: 1px solid black;
}
.formContainer {
margin-top: 20px;
}
input {
display: block;
margin: 10px;
}


JS

$(document).ready(function() {
var inputCount = $('.progInput').length;
function stepProgress() {
inputFilled = 0;
$('.progInput').each(function(i, e) {
if ($(e).val()) inputFilled++;
});
var pct = (inputFilled / inputCount) * 100;
$('#currentProgress').animate({
width: pct + "%"
}, 800);
if (pct === 100) {
$('#currentProgress').animate({
backgroundColor: '#608341'
});
} else {
$('#currentProgress').animate({
backgroundColor: '#00BFF2',
});
}
}
$('.progInput').change(function() {
stepProgress();
});
});


JSFiddle

https://jsfiddle.net/rsf6mzr1/

Answer

You can use css transitions like this:

Css:

#currentProgress {
  width: 0px;
  height: 100%;
  background-color: #00BFF2;

  transition: width .8s;
}

And script:

$(document).ready(function() {
  var inputCount = $('.progInput').length;
  function stepProgress() {
    inputFilled = 0;
    $('.progInput').each(function(i, e) {
      if ($(e).val()) inputFilled++;
    });
    var pct = (inputFilled / inputCount) * 100;
    $('#currentProgress').css('width', pct + "%");
    if (pct === 100) {
      $('#currentProgress').animate({
        backgroundColor: '#608341'
      });
    } else {
      $('#currentProgress').animate({
        backgroundColor: '#00BFF2',
      });
    }
  }
  $('.progInput').change(function() {
    stepProgress();
  });
});

With this script you only change width attr and css perform the animation.