Favorite Star Rating with jQuery

by Vincy. Last modified on July 6th, 2023.

This tutorial has a jQuery code for doing favorite star ratings. It displays a list of HTML stars by using li tags. These stars are highlighted using CSS and jQuery based on the user’s favorite rating.

View Demo

HTML Code for Displaying Rating Stars

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

rating

star-rating

<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 preserves the selected rating count on clicking stars.

jQuery Favorite Star Rating Functions

These are the jQuery functions we use in this example to handle favorite star ratings.

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 receive selected HTML element objects 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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page