bobby_bob
bobby_bob

Reputation: 3

Simple count using jQuery

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);
    });

Upvotes: 0

Views: 411

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 2

Related Questions