One way to implement the specific rating value from Ruby in HTML5 is by using the data-*
attribute, as shown in the rendered html below:
<span class='rating' data-rating='3.5'></span>
To dynamically set the appropriate image background position from a png sprite file, you can utilize a combination of javascript/jQuery. First, define the css properties for the selector .rating
to incorporate the sprite image. For instance, if you prefer to use big stars from the sprite, assign an ID
to the parent container:
#rateBig .rating {
background-image: url('images/rating.png');
background-repeat: no-repeat;
width: 84px;
height: 16px;
display: block;
}
Note the values for width: 84px;
and height: 16px;
correspond to the size of a big star stripe.
Assuming your HTML structure matches the defined CSS:
<ul id="rateBig">
<li>This line is rated 3.5 stars<br /><span class='rating' data-rating='3.5'></span></li>
</ul>
The following JavaScript code sets the backgroundPosition based on the data-* attribute value for the big stars:
<script>
var dataRating, bkPos;
function getRateImageBig(dataRating){
// Define background position for each rating
switch(dataRating){
case 1: bkPos = "0 -19px"; return bkPos; break;
case 1.5: bkPos = "0 -38px"; return bkPos; break;
// Other cases omitted for brevity
}
}
$(document).ready(function() {
$("#rateBig .rating").each(function(i){
var selector = $(this);
dataRating = selector.data("rating");
getRateImageBig(dataRating);
selector.css({"backgroundPosition": bkPos});
});
});
</script>
This approach can also be applied for small stars. Additionally, tools like spritecow online tool can assist in determining correct background positions for sprites.
View the DEMO HERE