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!

58 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

  9. 518700 42028Wow, incredible weblog structure! How long have you been running a blog for? you created running a blog look simple. The entire look of your website is magnificent, neatly as the content material! 418613

  10. Pingback: My Homepage
  11. Pingback: pigspin
  12. Pingback: lazywin888
  13. Pingback: โคมไฟ
  14. Es un gran recurso sobre salud.
    Siempre es importante estar informado sobre cuidados médicos.

    Información muy útil. Gracias.
    La información sobre laboratorios es esencial.
    Interesante punto sobre los análisis clínicos.
    Un tema de salud muy relevante hoy en día.
    Buen artículo sobre prevención.
    Esto hace que la información médica sea más accesible.

    Los laboratorios juegan un rol fundamental en la
    prevención de enfermedades.
    Este artículo está muy bien estructurado.
    La prevención es clave y este artículo lo deja claro.

    Me gusta cómo abordas el tema de los laboratorios.
    Siempre es bueno estar informado sobre temas de salud.

    Esto es justo lo que necesitaba leer.
    Un contenido que sin duda es valioso.
    Gracias por la información clara y directa.
    La salud es prioridad y esto lo deja claro.
    Un contenido excelente para entender mejor este tema.

    Gracias por enfocarte en este aspecto.
    Un artículo que todos deberíamos leer.
    Gracias por recordar lo importante que es esto.
    Gracias por compartir tu conocimiento sobre este tema.

    Gracias por la información tan bien explicada.
    Gracias por abordar este tema con tanta claridad.
    Es esencial saber más sobre este tema.
    Esto es lo que todos necesitamos saber.
    Un gran recurso para quienes buscan información confiable.

    Es importante estar bien informado sobre salud.
    Gracias por la información tan útil.
    Un artículo muy valioso sobre un tema importante.

    Gracias por compartir esta información tan necesaria.

    Es bueno ver artículos que se enfoquen en la prevención.
    Es un gran recurso para quienes quieren aprender
    más sobre salud.
    Un gran contenido sobre salud y bienestar.
    La salud es un tema que todos debemos tomar en serio.

    Un artículo muy interesante y bien explicado.
    La importancia de los laboratorios no puede subestimarse.

    Un gran recurso para la comunidad.
    Gracias por este artículo tan necesario.
    Un gran recurso para quienes buscan información confiable.

    Un tema muy importante y bien explicado.
    Un excelente artículo sobre salud y cuidados preventivos.

    Siempre es útil tener información clara sobre temas de
    salud.
    Es importante estar bien informado sobre salud y bienestar.

    Un tema vital y bien desarrollado en este artículo.
    Es fundamental entender esto y tu artículo ayuda mucho.
    Un excelente recurso para quienes buscan mejorar su salud.

  15. Pingback: pgslot
  16. I am curious to find out what blog system you have been using?

    I’m experiencing some minor security problems with my latest site and
    I would like to find something more safeguarded. Do you have any
    suggestions?

  17. Hey there I am so happy I found your blog, I really found you by error, while I was browsing on Google for something else, Anyways
    I am here now and would just like to say thanks for a tremendous post and a all round exciting blog (I also love
    the theme/design), I don’t have time to browse it all at the minute but
    I have saved it and also included your RSS feeds, so when I have
    time I will be back to read much more, Please do keep up
    the superb work.

  18. Pingback: Mostbet
  19. Pingback: pgslot
  20. What’s up i am kavin, its my first occasion to commenting anyplace, when i read this paragraph
    i thought i could also make comment due to this sensible piece of writing.

  21. A fascinating discussion is definitely worth comment.

    There’s no doubt that that you ought to write more on this subject matter,
    it might not be a taboo subject but usually
    folks don’t discuss these subjects. To the next! Best wishes!!

  22. Hello, I do believe your web site might be having browser compatibility issues.
    Whenever I take a look at your blog in Safari, it looks fine however, if opening in IE, it has some overlapping issues.
    I just wanted to give you a quick heads up! Other than that, great website!

  23. Hey there superb blog! Does running a blog such as this take a great deal of work?

    I have absolutely no knowledge of computer programming
    but I was hoping to start my own blog soon. Anyway, if you have any recommendations or tips for new blog owners please share.
    I understand this is off topic but I just wanted
    to ask. Many thanks!

  24. Наш сервис предлагает квалифицированный ремонт пылесосов Philips включая диагностику.

    Преимущества обращения к нам:

    Бесплатная диагностика

    Быстрые сроки восстановления работоспособности

    Доступные расценки

    Ремонт с выездом к клиенту для крупной техники

    Узнать больше или записаться на ремонт вы можете на нашем сайте [url=https://philips-remont-moskva.ru/]сервисный центр филипс ремонт кофемашины[/url].

    Доверьте свою технику профессионалам! Свяжитесь с нами для консультации – мы решим вашу задачу!

  25. компания ремонт окон спб: быстро, надёжно, с гарантией!
    Запотевшие стёкла, сквозняки, заедающие ручки? Наш сервисный центр в Санкт-Петербурге устранит любые неполадки за 1-3 часа! Бесплатный выезд мастера, точная диагностика, использование оригинальных комплектующих и гарантия до 2 лет — вот почему клиенты выбирают нас. Заказать [url=https://remont-okon-spb-nedorogo.ru/]окна сервисный мастер[/url] можно онлайн или по телефону: специалист приедет в удобное время, вернёт герметичность конструкциям и продлит их срок службы. Работаем 24/7, фиксированные цены, без скрытых наценок. Доверьте окна профессионалам — и забудьте о проблемах!

  26. Радуйтесь чистоте вашего дома без лишних усилий! Наша клининговая компания в Санкт-Петербурге предлагает первоклассные услуги уборки: от традиционной чистки до специализированных процедур. Мы сознаем, как необходимо возвращаться в уютное и прибранное пространство, поэтому наши профессионалы используют только безопасные и действенные средства. Жмите https://ubork-kompan24.ru – сколько стоит клининг в спб
    Поручите заботу о чистоте вашего дома нам и проводите время с близкими с удовольствием! Оформляйте заказ уборку у нас — и вы позабудете о пыли и неразберихе.

  27. Устали от бесконечной уборки? Передайте это профессионалам! Наша чистящая компания предлагает качественные услуги по уборке квартир, чтобы вы могли наслаждаться чистотой и уютом без дополнительных забот. Мы используем только безопасные и результативные средства, а наша команда профессиональных специалистов гарантирует безупречный результат. Переходите https://ubork-kompan24.ru Запишитесь на прием по уборке прямо сейчас также получите скидку в размере 10% суммы на первое посещение! Позвольте себе дополнительные часы для себя для главных дел и отдыха. Звоните команде или оставляйте заявки — чистота вашего дома в надежных руках!”

  28. Устали от непрекращающейся уборки? Поручите это экспертам! Наша уборочная компания сервисирует качественные услуги по уборке квартир, чтобы вы могли баловать себя чистотой и уютом без лишних хлопот. Мы используем только экологически чистые и действующие средства, а наша команда профессиональных специалистов предоставляет безупречный результат. Жмите генеральная уборка квартир спб
    Запишитесь на услуги чистоты прямо сейчас и получите скидку в размере 10% суммы на первое посещение! Позвольте себе больше свободного времени для главных дел и релаксации. Звоните команде или пишите — чистота вашего жилища в проверенных руках!”

  29. Ищешь свежие зеркала на Kraken — лучший российский даркнет-маркетплейс? Заходи на этот форум: https://krak-ssylka-na-sajt.biz/ Здесь ты получишь нужные зеркала для входа на Кракен.

    Kraken — это надёжный маркетплейс, на котором представлены различные предметы. Для того чтобы перейти на Кракен, требуются свежие адреса. На моём форуме ежедневно выкладываются новые адреса Кракена, чтобы мог перейти на маркетплейс без труда.

    Ни в коем случае не теряй время на выбор ссылок в сомнительных местах! Всё необходимое сразу доступно на этом форуме. Загляни и отыщи рабочие адреса на Кракен в 2025 году!

  30. Идеальная свежесть вашего дома или офиса — это гораздо ближе, чем вы предполагаете! Наша клининговая компания предлагает профессиональные услуги наведения порядка в Санкт-Петербурге. Мы внимательны о каждом уголке, освобождая вас от рутины и позволяя упиваться досугом. Используем только безопасные и действенные средства, а также передовые технологии для получения безукоризненного результата. Выбирайте https://clean-help24.ru – Мытье окон в квартире цены в СПб Наши козыри: Проверенные временем мастера чистоты, подстраиваемый под ваши нужды график и внимание к вашим пожеланиям к абсолютно всем. Переложите ответственность на наши плечи и просто расслабьтесь. Мы облегчим вашу рутину! Не упустите шанс улучшить свою жизнь и заказывайте уборку прямо сейчас!

  31. Наслаждайтесь свежестью вашего дома без лишних усилий! Наша клининговая компания в Санкт-Петербурге предлагает первоклассные услуги уборки: от обычной чистки до сложных процедур. Мы понимаем, как необходимо возвращаться в комфортное и аккуратное пространство, поэтому наши профессионалы используют только безопасные и эффективные средства. Перемещайтесь к https://spb24uslugi.ru/ Поручите заботу о чистоте вашего дома нам и проводите время с близкими с удовольствием! Оформляйте заказ уборку у нас — и вы позабудете о пыли и беспорядке.

  32. Наслаждайтесь свежестью вашего дома без лишних забот! Наша клининговая компания в Санкт-Петербурге предлагает качественные услуги уборки: от традиционной чистки до специализированных процедур. Мы сознаем, как важно возвращаться в комфортное и аккуратное пространство, поэтому наши профессионалы используют только безопасные и эффективные средства. Жмите https://spb24uslugi.ru/ Вверьте заботу о чистоте вашего дома нам и наслаждайтесь временем с любимыми с удовольствием! Заказывайте уборку у нас — и вы забудете о пыли и беспорядке.

  33. Устали от скучных уборок и бесконечной пыли? Клининговая компания в Санкт-Петербурге предлагает качественные услуги по уборке жилых и деловых помещений. Мы бережем о вашем времени, применяя только экологически чистые и действенные средства. Наша команда мастеров подарит вашему дому или офису сиянием и порядок, а вам — уверенность и спокойствие. Жмите Уборка ресторанов Вверьте наведение порядка нам и наслаждайтесь временем, разделенным с родными и друзьями! Запишитесь на безвозмездную консультацию прямо сейчас и получите бонусные предложения для новых клиентов. Чистота — это не просто работа, это наше призвание!

  34. Разыскиваете надежную помощь в наведении порядка квартиры в Санкт-Петербурге? Наша команда специалистов гарантирует чистоту и и порядок в вашем доме! Мы применяем только безопасные для здоровья и эффективные средства, чтобы вы могли вкушать свежестью без хлопот. Нажимайте https://profuslugi24.ru – Уборка дома санкт петербург Не прозевайте шанс сделать свою жизнь проще и удобнее.

  35. Ищете надежную помощь в наведении порядка квартиры в Санкт-Петербурге? Наша команда специалистов гарантирует чистоту и порядок в вашем доме! Мы используем только безопасные для здоровья и эффективные средства, чтобы вы могли вкушать свежестью без хлопот. Перемещайтесь к https://chisto-v-srok.ru – Клининг офиса после ремонта

Leave a Reply

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