I think this is the most common example, where you have two Star controls.
The first one represents an Average rating and is disabled by default,
while the second one is enabled, allowing the user to vote for an item.
In this example I will simply pass the selected value from right to left control, although in "real life",
you will have to submit selected value to the server and then use returned data to set the Stars accordingly.
The callback is fired each time an element is clicked and it has three arguments: Stars instance,
string representing clicked element ("star" or "cancel") and the Value assigned to the clicked element.
$("#stars-wrapper2").stars({ // already disabled via markup
inputType: "select",
split: 2,
captionEl: $("#stars-wrapper2-cap")
});
$("#stars-wrapper1").stars({
split: 2,
captionEl: $("#stars-wrapper1-cap"),
callback: function(ui, type, value){
$("#stars-wrapper2").stars("select", value);
$("#stars-wrapper2-red").html(value==ui.options.cancelValue ? "Rating removed" : "Rating saved! ("+value+")").stop().css("opacity", 1).fadeIn(30);
setTimeout(function(){ $("#stars-wrapper2-red").fadeOut(1000) }, 2000);
}
});
I've been pointed correctly that in previous example, the "Average rating" is rounded to the number of INPUTs only.
Frankly speaking, it wasn't my intention to add support for "Average rating" in this widget,
although I will show you yet another way how to obtain such functionality. This technique is based on two, overlaping DIVs.
NOTE: I removed all the useless stuff from this example - just to show you the rough idea, so it may work a little bit different from what you can see on this page.
Also, the rating counter will automatically reset after 20 votes.
<!-- example CSS declarations -->
<style type="text/css">
.stars-off, .stars-on {
position: relative;
height: 16px;
background: url(ui.stars.gif) repeat-x 0 -32px;
}
.stars-on {
position: absolute;
background-position: 0 -48px;
}
</style>
<!-- example DOM -->
Average: <span id="fake-stars-cap"></span>
<div id="fake-stars-off" class="stars-off" style="width:160px"><div id="fake-stars-on" class="stars-on"></div></div>
$("#stars-wrapper1").stars({
cancelShow: false,
captionEl: $("#stars-cap"),
callback: function(ui, type, value)
{
$.getJSON("ratings.php", {rate: value}, function(json)
{
$("#fake-stars-on").width(Math.round( $("#fake-stars-off").width() / ui.options.items * parseFloat(json.avg) ));
$("#fake-stars-cap").text(json.avg + " (" + json.votes + ")");
});
}
});
Let's say you can't use the callback function, but still need to access the particular Stars instance.
How to achieve this? The answer is in jQuery's internal $.data() function.