Rating System
Rating System using jQuery and Font-Awesome
by Puddster
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<i id="rating1" class="fa fa-star fa-5x"></i>
<i id="rating2" class="fa fa-star fa-5x"></i>
<i id="rating3" class="fa fa-star fa-5x"></i>
<i id="rating4" class="fa fa-star fa-5x"></i>
<i id="rating5" class="fa fa-star fa-5x"></i>
<i id="rating6" class="fa fa-star fa-5x"></i>
<i id="rating7" class="fa fa-star fa-5x"></i>
<i id="rating8" class="fa fa-star fa-5x"></i>
<i id="rating9" class="fa fa-star fa-5x"></i>
<i id="rating10" class="fa fa-star fa-5x"></i>
<hr />
<input type="text" id="overallScore" value="5.5" />
JavaScript
$(document).ready(function () {
$("[id^=rating]").css("cursor", "pointer").mousemove(function (e) {
// Get variables to calculate internal coordinates
var mouseX = e.pageX - $(this).offset().left,
starWidth = $(this).width();
// Fill up all previous stars
$(this).prevAll("i").removeClass("fa-star-half-full fa-star-o").addClass("fa-star");
// Check mouse position within the star and apply relevant class
if (mouseX / starWidth < 0.1) {
$(this).removeClass("fa-star-half-full fa-star").addClass("fa-star-o");
} else if (mouseX / starWidth < 0.65) {
$(this).removeClass("fa-star-o fa-star").addClass("fa-star-half-full");
} else {
$(this).removeClass("fa-star-half-full fa-star-o").addClass("fa-star");
}
// Empty all proceeding stars
$(this).nextAll("i").removeClass("fa-star-half-full fa-star").addClass("fa-star-o");
}).click(function () {
// Count the full stars and add 0.5 if there's a half-star
var score = $(".fa-star").length + ($(".fa-star-half-full").length / 2)
$("[id*=overallScore]").val(score);
}).parent().mouseleave(function () {
// Restore the star rating if the mouse leaves all rating stars
var score = $("[id*=overallScore]").val();
$("[id^=rating]").each(function (index) {
if (index <= Math.floor(score)) {
$(this).prevAll("i").removeClass("fa-star-half-full fa-star-o").addClass("fa-star");
$(this).nextAll("i").removeClass("fa-star-half-full fa-star").addClass("fa-star-o");
}
if ((score - index) === 0.5) {
$(this).removeClass("fa-star-half-full fa-star-o").addClass("fa-star-half-full");
} else if (score === "10") {
$(this).removeClass("fa-star-half-full fa-star-o").addClass("fa-star");
}
});
});
});