Search code examples
javascriptrating

How to make this javascript code better than?


I have code to render five star rating base on the rating, I think it very easy for everybody but I don't have any idea to make this code better.

@T.J. Crowder have the idea to solve this:

// Flags for whether to show stars, based on `average` being
// a fractional number `0 <= average < 5`
var stars = [
    average > 0,
    average > 1,
    average > 2,
    average > 3,
    average > 4
];

How to implement this or anyone have any ideas to make this code better?

var result = '';
var one_star = '';
var two_star = '';
var three_star = '';
var four_star = '';
var five_star = '';

if(data == 0) {}
else if(data == 1) {
    one_star = 'star-rating-on';
    two_star = '';
    three_star = '';
    four_star = '';
    five_star = '';
}
else if(data == 2) {
    one_star = 'star-rating-on';
    two_star = 'star-rating-on';
    three_star = '';
    four_star = '';
    five_star = '';
}
else if(data == 3) {
    one_star = 'star-rating-on';
    two_star = 'star-rating-on';
    three_star = 'star-rating-on';
    four_star = '';
    five_star = '';
}
else if(data == 4) {
    one_star = 'star-rating-on';
    two_star = 'star-rating-on';
    three_star = 'star-rating-on';
    four_star = 'star-rating-on';
    five_star = '';
}
else if(data == 5) {
    one_star = 'star-rating-on';
    two_star = 'star-rating-on';
    three_star = 'star-rating-on';
    four_star = 'star-rating-on';
    five_star = 'star-rating-on';
}

result += '<span class="star-rating-control">';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ one_star +'"><a title="Poor">1</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ two_star +'"><a title="OK/Fair">2</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ three_star +'"><a title="Good">3</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ four_star +'"><a title="Great">4</a></div>';
result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly '+ five_star +'"><a title="Excellent">5</a></div>';
result += '</span>';

Solution

  • what you want could basically be done just in a loop:

    var i
      , on
      , titles = [null, 'Poor', 'Ok/Fair', 'Good', 'Great', 'Excellent']
      , result = '<span class="star-rating-control">';
    for (i = 1; i <= 5; i++) {
      on = data >= i ? 'star-rating-on' : '';
      result += '<div class="star-rating rater-5 star star-rating-applied star-rating-readonly ' + on +'"><a title="' + titles[i] + '">' + i + '</a></div>'
    }
    result += '</span>';
    

    that is all you need, see a working example here (i set data to 3 in the example): http://jsfiddle.net/k7sVC/1/