I have been looking at jquery plugin and was wondering how to adapt that plugin to turn a number (like 4.8618164) into a 4.8618164 stars filled out of 5. Basically interpreting a number <5 into stars filled in a 5-star rating system using jQuery/JS/CSS.
Note that this would only display/show the stars rating from an already available number and not accept new ratings submissions.
Try this jquery function
FontAwesome CSS
You can download FontAwesome at http://fontawesome.io/
DEMO
You can do it with 2 images only. 1 blank stars, 1 filled stars.
Overlay filled image on the top of the other one. and convert rating number into percentage and use it as width of fillter image.
Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?
For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.
Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).
I ended up going totally JS-free to avoid client-side render lag. To accomplish that, I generate HTML like this:
To help with accessibility, I even add the raw rating value in the title attribute.
using jquery without prototype, update the js code to
I also added a data attribute by the name of data-rating in the span.
If you only have to support modern browsers, you can get away with:
You only need to convert the number to a
class
, e.g.class='stars-score-50'
.First a demo of "rendered" markup:
Then a demo that uses a wee bit of code:
The biggest downsides of this solution are:
width
on a pseudo-element).To fix this the solution above can be easily tweaked. The
:before
and:after
bits need to become actual elements in the DOM (so we need some JS for that).The latter is left as an excercise for the reader.