M-S M-S - 7 months ago 40
Javascript Question

How to calculate and display ratings for font-awesome using jQuery

I am trying to display the stars and append the

<i>
tag dynamically based on the count.

It's working fine, but the problem is if it has floating value then it displays the star in full, I need the star to be half (CSS class
fa-star-half-o
).

This is what I tried:



var ratingValue = 3.489;

for (var j = 0; j < ratingValue; j++) {
$(".rating").append('<i class="fa fa-star" aria-hidden="true"></i>');
}

<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>
<div class="rating">
</div>




Answer

You can achieve what you want like below,

var ratingValue = 3.489, rounded = (ratingValue | 0);
var decimal = ratingValue - rounded, $rating = $(".rating");

for (var j = 0; j < rounded ; j++) {
   $rating.append('<i class="fa fa-star" aria-hidden="true"></i>');
}

if(decimal) {
  $rating.append('<i class="fa fa-star-half" aria-hidden="true"></i>');
}

DEMO

Edit as per your new requirement,

There is no need for 2 different for loops (simple math is enough)

var ratingValue = 3.9, rounded = (ratingValue | 0);

for (var j = 0; j < 5 ; j++) {
  $(".rating").append(
         '<i class="fa '+ ((j < rounded) 
                  ? "fa-star" 
                  : ((((ratingValue - j) > 0) && ((ratingValue - j) < 1)) 
                     ? "fa-star-half-o" 
                     : "fa-star-o")) 
         +'" aria-hidden="true"></i>');
}

DEMO

Comments