I'm working on a simple star rating system, and before I move on to actually "tallying" the votes, which I figure I'll just do with $.ajax
, I wanted to make sure what I've done so far has been done as well as it can be.
JavaScript
//max number of stars
var max_stars = 5;
//add images to the ratings div
function fill_ratings() {
var $rating = $("#rating");
if($rating.length) {
for(i = 1; i <= max_stars; i++) {
$rating.append('<img id="' + i + '"src="star_default.png" />');
}
}
}
//variables...
var hovered = 0;
var has_clicked = false;
var star_clicked = 0;
function handle_ratings() {
if(has_clicked == true) {
for(i = 1; i <= star_clicked; i++) {
$('#rating img#' + i).attr('src', 'star.png');
}
}
$('#rating img').hover(function() {
hovered = Number($(this).attr('id'));
for(i = 1; i <= max_stars; i++) {
if(i <= hovered) {
$('#rating img#' + i).attr('src', 'star.png');
} else {
$('#rating img#' + i).attr('src', 'star_default.png');
}
}
}).click(function() {
//if they click a star, only set the stars to grey that are after it.
star_clicked = Number($(this).attr('id'));
has_clicked = true;
for(i = 1; i <= star_clicked; i++) {
$('#rating img#' + i).attr('src', 'star.png');
//handle the vote here. eventually.
}
}).mouseout(function() {
//if they haven't clicked a star, set all stars to grey.
if(has_clicked !== true) {
$('#rating img').attr('src', 'star_default.png');
} else {
//show their rating
for(i = 1; i <= max_stars; i++) {
if(i <= star_clicked) {
$('#rating img#' + i).attr('src', 'star.png');
} else {
$('#rating img#' + i).attr('src', 'star_default.png');
}
}
}
});
}
$(function() {
fill_ratings();
handle_ratings();
});
HTML
<div id="ratings"></div>
The code works, but I was wondering if anyone notices any code that I can improve. Also, is there anything wrong with the way it...looks? Should I be commenting more, indenting differently, or any other "formatting" type things?