vinnizworld
10/29/2012 - 10:16 AM

jQuery fivestar plugin

jQuery fivestar plugin

/* jQuery Fivestar rating plugin CSS */
ul.star-rating{
	list-style: none;
	margin: 5px 0 2px 0;
	padding: 0;
	width: 100px;
}

ul.star-rating.marBot{
	margin: 0 0 10px 0;
}

ul.star-rating li{
	color: black; 
	height: 13px;
	width: 14px;
	background-image: url(../img/icons/star-grey.png);
	float: left;
	padding-right: 3px;
	background-repeat: no-repeat;
	cursor: pointer;
}

ul.star-rating li.on{
	background-image: url(../img/icons/star-color.png);
}

ul.star-rating li.half{
	background-image: url(../img/icons/star-half.png);
}

ul.star-rating.inactive li{ cursor: default; }
/*-- jQuery Fivestar rating plugin CSS --*/

/* Contain floats: h5bp.com/q */
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
/*
 * Five Star Rating Plugin
 *
 * @team Softway Solution
 */

(function($){
	$.fn.fivestar = function(edit){
		if(edit === undefined){ edit = true }
		 var tmpl = $('<ul class="star-rating clearfix" ><li></li><li></li><li></li><li></li><li></li></ul>');
		this.each(function(){
			var self = $(this), val = this.value, rounded = parseInt(this.value);
			if( !(val >= 0 && val <= 5) || self.hasClass('fivestar') ){ return; }
			var cur = tmpl.clone();
			self.after(cur).hide().addClass('fivestar');
			cur.attr('title', 'Rating: ' + parseFloat(val || 0).toFixed(1));
			if( val - rounded > 0 ){ cur.find('li:eq(' + (rounded) + ')').addClass('half'); }
			cur.find('li:lt(' + rounded + ')').addClass('on');

			if( !edit ){ cur.addClass('inactive'); return; }
			cur.on('click', 'li',function(){
				var idx = $(this).index() + 1,
				parent = $(this).parent(),
				off = parent.find('li:gt(' + (idx - 1) + ')'),
				on = parent.find('li:lt(' + idx + ')');
				parent.attr('title', 'Rating: ' + idx);
				self.val(idx).trigger('change');	
				off.removeClass('on half');
				on.addClass('on').removeClass('half');
			});
		});
		return this;
	}
})(jQuery);