views:

1010

answers:

2

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. Any help would be greatly appreciated. Thanks.

+3  A: 

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).

paxdiablo
Sigh, beat me to it.
Michael
+32  A: 

Here's a solution for you, using only one very tiny and simple image and two automatically generated span elements:

CSS

span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

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

Image

alt text

jQuery

$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // 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 = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size row:

val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */

HTML

<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>

Usage

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

Output

Image from fugue icon set (www.pinvoke.com)

Demo

http://www.ulmanen.fi/stuff/stars.php

This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.


A small explanation on how the stars are presented might be in order.

The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:

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

The outer span gets a background-position of 0 -16px. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x, it will only show 5 gray stars.

The inner span on the other hand has a background-position of 0 0 which makes only the yellow stars visible.

This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.

Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.

But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.

Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px, so that people with CSS turned off would at least see the floating point number instead of the stars.

Hopefully that made some sense.


Updated 2010/10/22

Now even more compact and harder to understand! Can also be squeezed down to a one liner:

$.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
}
Tatu Ulmanen
+1, much more elegant (and complete) than mine. I'm almost ashamed to leave my answer here next to this one. But I will (for now) since it has more positive than negative rep :-)
paxdiablo
Very clever indeed
Justin Johnson
@Tatu, any chance of fleshing it out a bit more with *how* this works. My knowledge of jQuery is just a tad short to totally get it. I think I understand how the CSS works with repeating in the x direction and the 16*5=80 bit and how you adjust the width of the yellow-star image, but how are you overlaying the two images on top of each other from a single image that has one star above the other? Does the -16px bring the gray star up to the same level as the yellow?
paxdiablo
Thanks for the update, @Tatu, that makes a lot more sense to me now. Unfortunately I'd already given you a +1 so I can't do it again but hopefully the explanation will earn you some more (well-earned) rep. Cheers.
paxdiablo
@paxdiablo and others, thanks for the support. Perhaps I should make this a proper jQuery plugin as this technique seems to come as a surprise to most :)
Tatu Ulmanen
@Tatu, thanks immensely. The existing five star plugins all seem to want a form which is fine for inputing a rating, but way overkill to change the representation of a number.
vfilby
vfilby, glad to be of assistance :)
Tatu Ulmanen
Tatu, I'm using your stars plugin inside ajax tooltips generated by the qTip jQuery plugin. In the beggining it works well, but as you mouse over a few links and get the tooltips, it appears the width of the yellow stars layer does not get reset, therefor something with a rating of 3 will show five gold stars. Is there a way to reset the width of the yellow layer after the tooltip closes?
Mel
@Mel, an easy solutions seems to be to run this snippet every time you open the tooltip: `$('.tooltip .stars').html(4.5354).stars();`. That will destroy the current stars, populate the container with a new value and then turn that value into stars.
Tatu Ulmanen
Tatu, thanks. I was wrong: I have five links and each creates a tooltip. As you mouseover from first to last, each tooltip is created and the stars display correctly. But as each new tooltip is created, it erases the width value for all the other previously created tooltips: the <span style=""></span> contains no width value. Moving back to a previous tooltip does not restore the width value. I tried your suggestion, but I don't think I'm doing it right. My code: $(this).qtip({ content: { url: 'data.cfc' }, api :{ onContentUpdate : function(){ //stars $('span.stars').stars();}
Mel
I'm just now coming across this and it's nice.
vol7ron
@vol7ron, thanks, hope you found this useful!
Tatu Ulmanen