How to create a simple “5 Star Rating”

Here we go for a simple 5 star rating.

Output:

output

HTML:

<div ratingamount="5" maxrating="10"></div>

JS:

//Rating Star JS
$('.ratingstar').each(function(){
  var ratingamount = $(this).attr('ratingamount');
  var maxrating = $(this).attr('maxrating');
  $(this).html('<a id="rstar_1" class="rstar"></a>'
              +'<a id="rstar_2" class="rstar"></a>'
              +'<a id="rstar_3" class="rstar"></a>'
              +'<a id="rstar_4" class="rstar"></a>'
              +'<a id="rstar_5" class="rstar"></a>');
  var perstar_value = (maxrating / 5);
  var k = ratingamount;
  for (i=1; i<=5; i++) {
    var step_val = i * perstar_value;
    if(step_val <= ratingamount) {
      $(this).find('#rstar_'+i).addClass('full');
    } else if((step_val > ratingamount) & (k > 0)) {
      $(this).find('#rstar_'+i).addClass('half');
    } else {
      $(this).find('#rstar_'+i).addClass('empty');
    }
    k = k - perstar_value;
  }
});

Image for CSS:

rating

CSS:

/* Rating Star CSS */
.ratingstar {
  display: inline-block;
}
.ratingstar .rstar{
  background: url(rating.png) scroll no-repeat 0 0 transparent;
  display: inline-block;
  width: 24px;
  height: 24px;
}
.ratingstar .rstar.full {
  background-position: 0 0;
}
.ratingstar .rstar.half {
  background-position: 0 -24px;
}
.ratingstar .rstar.empty {
  background-position: 0 -48px;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s