optimize jquery progress bar04:33

  • 0
Published on May 24, 2017

Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

In this video we will discuss how to enhance and optimize the jquery progress bar that we created in Part 48 of jQuery tutorial.

At the moment the progress bar always counts from 1. For example
1. When you select 30%, it starts to count from 1 to 30 which is good.
2. Now if you select 70%, it starts again from 1 and counts all the way till 70, instead of continuing to count from 30 to 70.

The following code counts from the previous point. For example
1. If you select 30% first, it starts to count from 1 to 30. Now if you select 90, it counts from 30 to 90.
2. At this point, if you select 20%, it counts down from 90 to 20.

Replace < with LESSTHAN symbol and > with GREATERTHAN symbol

$(document).ready(function () {
var currentPercentage = 0;
var previousPercenage = 0;

$(‘#myButton’).click(function () {
previousPercenage = currentPercentage;
currentPercentage = $(‘#ddlPercent’).val();
animateProgressBar(previousPercenage, currentPercentage);
});

function animateProgressBar(previousPercenage, currentPercentage) {
$(‘#innerDiv’).animate({
‘width’: (500 * currentPercentage) / 100
}, 2000);

if (previousPercenage > currentPercentage)
currentPercentage = currentPercentage – 1;

$({ counter: previousPercenage }).animate({ counter: currentPercentage }, {
duration: 2000,
step: function () {
$(‘#innerDiv’).text(Math.ceil(this.counter) + ‘ %’);
}
});
}
});

The above code can be optimized as shown below. This optimization is suggested by Aptem A, one of our youtube subscribers. This is great, thanks to him for his valuable contribution.

$(document).ready(function () {
$(‘#myButton’).click(function () {
animateProgressBar($(‘#ddlPercent’).val());
});

function animateProgressBar(currentPercentage) {
$(“#innerDiv”).animate({ “width”: (currentPercentage * 500) / 100 }, {
duration: 3000,
step: function (now, fx) {
$(“#innerDiv”).text(Math.ceil((now / 500) * 100) + ‘ %’);
}
});
}
});

step option of the animate function can be used to define a function that gets called after each step of the animation. This method has 2 parameters – now & tween.

1. now – contains the value being animated
2. tween – is a complex object and contains several properties. A few are listed below. For the complete list set a break point and inspect the object

elem – The DOM element being animated
now – The value the animation is currently at
end – The value the animation will end at

jQuery animate method documentation

https://cafeadobro.ro/

https://www.stagebox.uk/wp-includes/depo10-bonus10/

https://iavec.com.br/

Enjoyed this video?
"No Thanks. Please Close This Box!"