0

I have a set of questions and want to display a simple progress counter above them. The code below works fine but I was wondering if somebody could advise on refactoring as theres got to be a better way of achieving this.

    var totalCount = $('#questions li').length,
        count = 1;
    $('.progress').html("Question " + count + " of " + totalCount);                 

    // Increment by 1 on each click
    $('.btn-next').click(function(){                        
        count ++ ;

        // remove current count
        $('.progress').empty();

        // drop in new count
        $('.progress').html("Question " + count + " of " + totalCount); 
    });

    // Decrease by 1 on each click
    $('.btn-prev').click(function(){
        count -- ;

        // remove current count
        $('.progress').empty();

        // drop in new count
        $('.progress').html("Question " + count + " of " + totalCount);
    });

1 Answer 1

2

You can DRY that code up quite a lot. Try this:

var totalCount = $('#questions li').length + 1, // add 1 as .length is 0 based
    count = 1;

$('.btn-next, .btn-prev').click(function(){                        
    count = $(this).hasClass('btn-next') ? count - 1 : count + 1;
    $('.progress').html("Question " + count + " of " + totalCount) 
});

Note that you don't need the empty() as you're replacing the html() anyway.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Rory When I run your script this is the output <div class="progress">Question NaN of 17</div> Any idea what NaN is?
NaN means the result is not a number - usually from trying to perform a math operation on a string and an integer. Can you put your code into a jsfiddle.net so I can see what's happening?
@bobby_bob sorry that was my mistake - you don't need the var keyword on the count variable within the click handler: jsfiddle.net/k4Ptg/5 I'll update my answer
@ Rory . . Spot on! fairly new to jQuery but when you receive help like this it makes the learning process that little bit easier. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.