Home » Tutorials » JavaScript » Turn A Number Into Star Rating Display in 5 Minutes Using jQuery

Turn A Number Into Star Rating Display in 5 Minutes Using jQuery

Turn A Number Into Star Rating Display in 5 Minutes Using jQuery

Let say you have a list of rating value inside your loop and you need to convert these rating value into a graphical element, for example: ★★★☆☆.

In this article, I will show you how to turn a number into Star Rating Display by using jQuery.

Setup

First, set up the icon font for the Star icon. All you need to do is include a single line of HTML into your document <head>:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

Second, write a function to parse & convert a number into Star Rating display:

function star(rate) {
    var starHTML = '';
    var rate = parseInt(rate);
    var increment = 0;
    var max = 5; // maximum rating

    while(increment < rate) {
      starHTML += '<i class="material-icons orange">grade</i>';
      increment++;
    }

    while(max > rate) {
      starHTML += '<i class="material-icons gray">grade</i>';
      max--;
    }
    return starHTML;
  };

In the star function, we’ve defined following variables:

  • starHTML – to incorporate the star icon.
  • rate – to convert the parameter (rate) into integer.
  • increment – an increment variable
  • max – the maximum star icon that we want to display

Then, we have 2 blocks of while loop statement. The first one is to generate orange star icon, while the second is to generate gray star icon.

Once complete, we return starHTML from the star function.

Third, declare CSS styles for the star icon:

.gray {
  color: gray;
}
.orange {
  color: orange;
}

That’s it!
We’ve done everything! Let’s see how to use it!

Using star Function

In this example, we have an object that contains 2 customer reviews.

We iterate with a for loop, and calling star function on every iteration.

Lastly, we append the snippet into the StarPlaceholder div.

<script>
var obj = {
  1: {
    rating: 5,
    title: 'Like it so much!'
  },
  2: {
    rating: 3,
    title: 'Overall is ok.'
  }
};

var snippet = '';
for (var key in obj) {
  snippet += '<div>' + star(obj[key]['rating']) + '</div>';
}

$('#StarPlaceholder').append(snippet);
</script>

Conclusion

You’ve just learned how to turn a number into Star Rating by using jQuery in just only 5 minutes!

Hope you enjoy this tutorial and please let me know in the comments what you would use this for 🙂