5 Star Rating System with JavaScript, HTML, and CSS



In this video we learn how to create a 5 star rating system using JavaScript, HTML, and CSS. JavaScript mainly runs the show here so this is also a good tutorial on JavaScript!

This star rating system works like a rectangular progress bar with stars overlaid on top of is so it looks like a star rating system.

Step 1: Get a Star Image

For this to work the star image needs to have a background, around the star out line of white. The inside of the star in the image needs to be transparent. Here is the image I used for this video.

star outline

 

Step 2: Code It Up!

This star rating system mainly runs on JavaScript. The only HTML we will need will be a container element that the JavaScript can reference for writing the star system out to the DOM. The JavaScrtpt is setup to reference the DOM element by id. On page load, a new star rating system is created. When the new rating system gets created we can pass along a number of variables to specify how we want each rating system setup. Here is the code, I made lots of comments so it should be pretty easy to pick upon how the code works.

<!DOCTYPE html>
<html>
    <head>
	<title>Star Rating System</title>
	<meta charset="utf-8" />
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script>
		// create object
		var starRating = ( function() {

			/**
			 * Constructor function
			 *
			 * @param Object args
			 *
			 * @return Object
			 */
			var starRating = function( args ) {
				// give us our self
				var self = this;

				// set global vars for our object
				self.container = jQuery( '#' + args.containerId );
				self.containerId = args.containerId;
				self.starClass = 'sr-star' + args.containerId;
				self.starWidth = args.starWidth;
				self.starHeight = args.starHeight;
				self.containerWidth = args.starWidth * 5;
				self.ratingPercent = args.ratingPercent;
				self.newRating = 0;
				self.canRate = args.canRate;

				// draw the 5 star rating system out to the dom
				self.draw();

				if ( self.canRate ) { // do other things if user can rate
					if ( typeof args.onRate !== 'undefined' ) { // bind custom function
						self.onRate = args.onRate;
				    }

					jQuery( '.' + self.starClass ).on( 'mouseover', function() { // mouseover a star
						// determine the percent width on mouseover of any star
						var percentWidth = 20 * jQuery( this ).data( 'stars' );

						// set the percent width  of the star bar to the new mouseover width
						$( '.sr-star-bar' + self.containerId ).css( 'width', percentWidth + '%' );
					});

					jQuery( '.' + self.starClass ).on( 'mouseout', function() { // mouseout of a star
						// return the star rating system percent to its previous percent on mouse out of any star
						jQuery( '.sr-star-bar' + self.containerId ).css( 'width', self.ratingPercent );
					});

					jQuery( '.' + self.starClass ).on( 'click', function() { // click on a star
						// ner rating set to the number of stars the user clicked on
						self.newRating = jQuery( this ).data( 'stars' );

						// determine the percent width based on the stars clicked on
						var percentWidth = 20 * jQuery( this ).data( 'stars' );

						// new rating percent is the number of stars clicked on
						self.ratingPercent = percentWidth + '%';

						// set new star bar percent width
						$( '.sr-star-bar' + self.containerId ).css( 'width', percentWidth + '%' );

						// run the on rate function passed in when the object was created
						self.onRate();
					} );	
				}
			};

			/**
			 * Draw html out to the page
			 *
			 * @param void
			 *
			 * @return void
			 */
			starRating.prototype.draw = function() {
				var self = this;
				var pointerStyle = ( self.canRate ? 'cursor:pointer' : '' );
				var starImg = '<img src="staroutline.png" style="width:' + self.starWidth + 'px" />';
				var html = '<div style="width:' + self.containerWidth + 'px;height:' + self.starHeight + 'px;position:relative;' + pointerStyle + '">';

				// create the progress bar that sits behinde the png star outlines
				html += '<div class="sr-star-bar' + self.containerId + '" style="width:' + self.ratingPercent + ';background:#FFD700;height:100%;position:absolute"></div>';

				for ( var i = 0; i < 5; i++ ) { // add each star to the page
					var currStarStyle = 'position:absolute;margin-left:' + self.starWidth * i + 'px';
					html += '<div class="' + self.starClass + '" data-stars="' + ( i + 1 ) + '" style="' + currStarStyle + '">' + 
						starImg + 
					'</div>';
				}

				html += '</div>';

				// write out to the dom
				self.container.html( html );
			};

			// return it all!
			return starRating;
		} )();

		$( function() {
			var rating = new starRating( { // create first star rating system on page load
				containerId: 'star_rating', // element id in the dom for this star rating system to use
				starWidth: 100, // width of stars
				starHeight: 100, // height of stars
				ratingPercent: '50%', // percentage star system should start 
				canRate: true, // can the user rate this star system?
				onRate: function() { // this function runs when a star is clicked on
					console.log( rating );
					alert('You rated ' + rating.newRating + ' starts' );
				}
			} );

			var rating2 = new starRating( { // create second star rating system on page load
				containerId: 'star_rating2', // element id in the dom for this star rating system to use
				starWidth: 100, // width of stars
				starHeight: 100, // height of stars
				ratingPercent: '20%', // percentage star system should start 
				canRate: true, // can the user rate this star system?
				onRate: function() { // this function runs when a star is clicked on
					console.log( rating2 );
					alert('You rated ' + rating2.newRating + ' starts' );
				}
			} );
		} );
	</script>
    </head>
    <body>
	<!-- first continer element for the first star rating system-->
	<div id="star_rating">
	</div>

	<br />
	<br />

	<!-- second continer element for the first star rating system-->
	<div id="star_rating2">
	</div>
    </body>
</html>

Run code and you should see two fully functional 5 Star Rating systems like in the image below!

5 Star Rating System Browser

Here are some helpful links relating to this blog post.

Live Demo

YouTube Video

Code on GitHub

That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!

13 comments

  1. Hello, you used to write fantastic, but the last several posts have been kinda boring?I miss your super writings. Past few posts are just a little bit out of track! come on!

  2. Thanks for your text. I would like to say that the health insurance brokerage service also works best for the benefit of the actual coordinators of your group insurance cover. The health agent is given a list of benefits wanted by someone or a group coordinator. Exactly what a broker can is search for individuals or even coordinators that best match those desires. Then he reveals his referrals and if each party agree, the actual broker formulates legal contract between the 2 parties.

  3. Hello just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Opera. I’m not sure if this is a format issue or something to do with internet browser compatibility but I figured I’d post to let you know. The design look great though! Hope you get the problem solved soon. Cheers

  4. My brother recommended I might like this website. He was totally right. This post truly made my day. You cann’t imagine simply how much time I had spent for this information! Thanks!

  5. I have been absent for a while, but now I remember why I used to love this blog. Thanks , I抣l try and check back more frequently. How frequently you update your site?

  6. Thanks for the suggestions shared using your blog. One more thing I would like to express is that weight loss is not about going on a dietary fad and trying to shed as much weight as you’re able in a couple of days. The most effective way to lose weight is by acquiring it slowly but surely and obeying some basic recommendations which can help you to make the most from your attempt to shed pounds. You may learn and already be following most of these tips, yet reinforcing awareness never damages.

  7. Thanks for the auspicious writeup. It in truth was once a entertainment account it. Look complex to more delivered agreeable from you! However, how could we keep in touch?

  8. Jaxx Wallet is an excellent multi-currency crypto wallet
    that allows users to manage digital assets easily and securely.
    Its user-friendly interface and multi-platform support make it an ideal choice.
    For more information, visit: Jaxx Wallet

Leave a Reply

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