Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

optimize jquery progress bar

Suggested Videos
Part 46 - jquery animate function
Part 47 - jquery animation queue
Part 48 - Simple jquery progress bar



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.

$(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.

now contains the value being animated
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
http://api.jquery.com/animate/

jQuery tutorial for beginners

4 comments:

  1. I noticed that on IE 11 still counting from 1 to the new completed percentage.

    I tried like this:


    function animateProgressBar(currentPercentage) {
    $("#innerDiv").animate({ "width": (currentPercentage * 500) / 100 }, {
    duration: 2000,
    step: function () {
    $(this).text(Math.ceil(($(this).width() / 500) * 100) + ' %');
    }
    });
    }


    Thank you for your great work.
    You are the best trainer.

    ReplyDelete
  2. Far easier to use just one variable and the always function


    "use strict";

    function displayInDivMsg(str) {
    $('#divResult').html($('#divResult').html() + str + '
    ');
    }

    $(document).ready(function () {

    var currentPercentage = 1; // ADDED

    function animateProgreesBar(percentageComplete) {

    displayInDivMsg('animateProgressBar called');

    $("#innerDiv")
    .css('position', 'absolute') // this needs to be set to allow animation to work
    .animate({ 'width': ((percentageComplete * 500) / 100) }, 2500);

    $({ counter: currentPercentage }) // MODDED
    .animate(
    {
    counter: percentageComplete
    },
    {
    duration: 2500,
    step: function () {
    $('#innerDiv').text(Math.ceil(this.counter) + ' %');
    },
    always: function () {
    displayInDivMsg('Completed Animation, currentPercentage=' + this.counter);
    currentPercentage = this.counter; // ADDED
    }
    });

    };

    $('#myButton').on('click', function () {
    var ddlPercentageComplete = $('#ddlPercentage');
    animateProgreesBar($('#ddlPercentage').val());
    displayInDivMsg('button clicked +' + $('#ddlPercentage').val() + '+');
    });
    });

    ReplyDelete
  3. Hi there, thank you very much for all tutorials and examples. Here's another way to get the same result, in three lines:

    1. var currentValue = $("#innerDiv").text();

    2. var position = (currentValue == "") ? 1 : parseInt(currentValue.substr(0, currentValue.indexOf("%")));

    3. percentageCompleted = (position > percentageCompleted) ? --percentageCompleted : percentageCompleted;

    Then, in the "counter" part, just put "position" instead of number "1". Like this:
    before - $({ counter: 1}).animate.....the rest of code
    after - $({ counter: position }).animate....the rest of code

    Thanks!

    ReplyDelete
  4. dropdown Id should be ddlPercentage as per previous video.

    ReplyDelete

It would be great if you can help share these free resources