Recently, I have been eager to convert a number into a star rating and stumbled upon this helpful post here: . The post perfectly explains what I am looking to achieve. Despite following the instructions provided, I am facing difficulties getting it to function properly in my local environment. Therefore, I am reaching out for assistance. Below is my attempt:
$.fn.stars = function() {
return $(this).each(function() {
// Extract the value
var val = parseFloat($(this).html());
// Ensure the value falls within 0 - 5 range, multiply to determine width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars container
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
}
$(function() {
console.log("Calling stars()");
$('.results-contents span.stars').stars();
});
.results {
font-size: 0;
padding-bottom: 16px;
}
.results-content {
font-size: 13px;
display: inline-block;
margin-left: 20px;
vertical-align: top;
}
.results .results-content span.stars span.stars span {
background: url('/resources/graphics/stars-icons.png') 0 -36px repeat-x;
width: 175px;
height: 80px;
}
.results .results-content span.stars {
max-width: 80px;
background-position: 0 0;
}
<script type="text/template" id="results-template">
<div class="results">
<div class="results-content">
<span class="stars">4.0</span>
</div>
</div>
</script>
Star Image:
https://i.sstatic.net/rwkqF.png
My intention was to display empty stars initially, then overlay orange stars based on the rating to represent full and half-star ratings. However, all I see is a number displayed. Although my console.log
appears to be functioning, the rendering of the image and calculation of star ratings seem to be problematic. Any assistance would be highly appreciated. Thank you!