Star Rating Display

Categories: jQuery.

Add a neat star rating symbol to your articles. This example does not allow the user to change the rating.

Sometimes articles and items are given a star rating using a row of stars as can be seen in this example on my home web site. This method will not allow the viewer to change the rating.

The code below is contained in a separate file or within <script></script> tags.

jQuery.fn.stars = function() {
 return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        val = Math.round(val * 2) / 2; /* To round to nearest half */

        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;

        // Create stars holder
        var $span = $('').width(size);

        // Replace the numerical value with stars
        jQuery(this).html($span);
    });
}

The following CSS is required to display the star image. Download the star image by right clicking on members.optusnet.com.au/~glenneaton/images/stars.png and chose “Save link as…” and save it to your website’s images folder.

/*CSS for the star ratings*/ 
    span.stars, span.stars span { 
    display: block; 
    width: 80px; 
    height: 16px; 
    background-image: url(images/stars.png); 
    background-repeat: repeat-x; background-position: 0 -16px;  
} 

span.stars span { 
    background-position: 0 0; 
}

Towards the bottom of your page insert the following code:

<script type="text/javascript" language="JavaScript">

      jQuery(function() {
           jQuery('span.stars').stars();
      });

</script>

Once set up insert the following to display your stars. The number is the number of stars to display.

<p><span class="stars">4.5</span></p>

WordPress

If you are using WordPress an easier way to add star ratings is to use the plugin Yet Another Stars Rating. Not only does it do a nice row of stars but it also allows Google to find ratings of whatever you have rated. Highly recommended.

Leave a Reply