Favorite Star Rating with jQuery

In this tutorial, we are having an jQuery code for doing favorite star rating. It displays list of HTML stars by using li tags. These stars are highlighted by using CSS and jQuery based on the favorite rating selected by the user.

rating

star-rating

View DemoDownload

HTML Code for Displaying Rating Stars

This HTML code displays list of rating star by  using HTML star entity and LI tags.

<input type="hidden" name="rating" id="rating" />
<ul onMouseOut="resetRating();">
  <li onmouseover="highlightStar(this);" onmouseout="removeHighlight();" onClick="addRating(this);">★</li>
  <li onmouseover="highlightStar(this);" onmouseout="removeHighlight();" onClick="addRating(this);">★</li>
  <li onmouseover="highlightStar(this);" onmouseout="removeHighlight();" onClick="addRating(this);">★</li>
  <li onmouseover="highlightStar(this);" onmouseout="removeHighlight();" onClick="addRating(this);">★</li>
  <li onmouseover="highlightStar(this);" onmouseout="removeHighlight();" onClick="addRating(this);">★</li>
</ul>

The hidden input is used to preserve the selected rating count on clicking stars.

jQuery Favorite Star Rating Functions

These are the list of jQuery functions we are using in this example to handle favorite star rating.

function highlightStar(obj) {
	removeHighlight();		
	$('li').each(function(index) {
		$(this).addClass('highlight');
		if(index == $("li").index(obj)) {
			return false;	
		}
	});
}

function removeHighlight() {
	$('li').removeClass('selected');
	$('li').removeClass('highlight');
}

function addRating(obj) {
	$('li').each(function(index) {
		$(this).addClass('selected');
		$('#rating').val((index+1));
		if(index == $("li").index(obj)) {
			return false;	
		}
	});
}

function resetRating() {
	if($("#rating").val()) {
		$('li').each(function(index) {
			$(this).addClass('selected');
			if((index+1) == $("#rating").val()) {
				return false;	
			}
		});
	}
}

In these functions, we are receiving selected HTML element object from the function call and change the star status based on the rating stars selected.

Star Rating Styles

We are using these styles in this star rating example.

li{display: inline-block;color: #F0F0F0;text-shadow: 0 0 1px #666666;font-size:30px;}
.highlight, .selected {color:#F4B30A;text-shadow: 0 0 1px #F48F0A;}

View DemoDownload

This jQuery code tutorial was published on November 10, 2014.

↑ Back to Top