Search code examples
jqueryprogress-barprogress

jQuery: progress bar progressing with each click


so I am trying to create a progress bar that will show a users current step number and a progress bar that will fill or unfill based on whether the user clicks "next" or "back".

here is my jQuery:

    var totalSteps = 30;
    var barWidth = $('.barWrap').width();
    var prog = barWidth/totalSteps;
    var currentValue = parseInt($("#stepNum").text(),10);
    var nextValue = currentValue + 1;
    var prevValue = currentValue - 1;

    // console.log(perc);

    $('#bar').css('width', prog);

    $('#nextNav').click(function(){
        $('#bar').css('width', prog + prog);
        $("#stepNum").text(nextValue);
    });

    $('#backNav').click(function(){
        $('#bar').css('width', prog - prog);
        $("#stepNum").text(prevValue);
    });

It works somewhat when you click next the progress bar fills with the correct amount of fill color based on the total steps specified (totalSteps = 30) and the step number changes.

But when I click "next" again nothing changes and when I click back the step number changes to 0 and the progress bar is empty.

So I need it to add the chunk and change the number up when "next" is clicked and remove the chunk and change the number down when "back" is clicked.

Here is a fiddle with all the code.

Thanks for any help.


Solution

  • You aren't updating any of your variables. Try this (I also added some logic to make sure it doesn't go out of bounds):

    https://jsfiddle.net/4xdbopgn/5/

    var totalSteps = 30;
    var barWidth = $('.barWrap').width();
    var prog = barWidth/totalSteps;
    var currentValue = 1;
    var maxValue = 30;
    
    $('#bar').css('width', prog);
    
    $('#nextNav').click(function(){
        currentValue++;
        if (currentValue > maxValue)
            currentValue = maxValue;
    
        $('#bar').css('width', prog * currentValue);
        $("#stepNum").text(currentValue);
    });
    
    $('#backNav').click(function(){
        currentValue--;
        if (currentValue < 1)
            currentValue = 1;
    
        $('#bar').css('width', prog * currentValue);
        $("#stepNum").text(currentValue);
    });