Dynamic Star Rating in JavaScript

Dynamic Star Rating in JavaScript
Code Snippet:Animated Star Rating ⭐
Author: Camille
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 2,204
License: MIT
Edit Code online: View on CodePen
Read More

This code allows you to create a dynamic star rating system using JavaScript. With this code, you can display animated stars and interactively set the rating by clicking on the stars. The stars will animate and change appearance based on the selected rating. It is useful if you want to add a visually appealing star rating feature to your website or application.

The stars are animated and have a sparkle effect, making the rating experience more engaging for users. The code also includes random star sparkles when hovering over the stars. Customize the styling and behavior to fit your specific requirements.

How to Create Dynamic Star Rating in Javascript

1. First, let’s set up the basic HTML structure for our star rating system. The <ul> element represents an unordered list that will hold the star elements. Each star is represented by an <li> element with a class of “off” and an onClick attribute that calls the setScore() function with the respective rating value.

<main>
	<div>
		<h1>Animated Stars</h1>
		<ul data-score="1">
			<li class="off" onClick="setScore(1)"></li>
			<li class="off" onClick="setScore(2)"></li>
			<li class="off" onClick="setScore(3)"></li>
			<li class="off" onClick="setScore(4)"></li>
			<li class="off" onClick="setScore(5)"></li>
		</ul>
	</div>
</main>

2. Now, let’s style the star rating system using the following CSS styles. Feel free to customize the CSS styles to match your design preferences. You can modify the colors, sizes, animations, or any other visual aspects of the star rating system.

@charset "UTF-8";
@import url("https://fonts.googleapis.com/css2?family=Orbit&display=swap");
body {
  background: #ECE5F0;
  margin: 0;
  padding: 0;
  font-family: "Orbit";
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100vw;
}

h1 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

main {
  background: #1B1B1E;
  color: white;
  min-width: 50%;
  margin: auto;
  border-radius: 10px;
  padding: 3em 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  border: 2px solid #FF5E5B;
  /*box-shadow: 0 10px 30px #FF5E5B;*/
}

ul {
  list-style-type: none;
  display: flex;
  padding: 0;
}

li {
  font-size: 300%;
  position: relative;
  transition: 0.2s ease-in all;
}
li:not(.off) {
  animation: spin 0.5s;
}
li.off {
  opacity: 0.25;
}
li.off:after {
  animation: fade-down 1s forwards;
}
li:before {
  content: "⭐";
}
li:after {
  content: "⭐";
  position: absolute;
  top: 0;
  left: 0;
}
li:hover {
  opacity: 0.7;
  cursor: pointer;
  transform: scale(1.05) rotate(5deg);
}
li span {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 10%;
  opacity: 0;
  animation: pew 1s forwards;
  animation-delay: var(--d, 0ms);
}

@keyframes pew {
  from {
    left: 50%;
    top: 50%;
    opacity: 0;
    font-size: 10%;
  }
  10% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
  80% {
    opacity: 0;
  }
  99% {
    left: var(--l, 150%);
    top: var(--t, 150%);
    opacity: 0;
    font-size: 50%;
  }
  to {
    opacity: 0;
    font-size: 100%;
  }
}
@keyframes fade-down {
  to {
    transform: translateY(100px) scale(1.5) rotate(90deg);
    opacity: 0;
  }
}
@keyframes spin {
  from {
    transform: rotateY(0deg);
  }
  to {
    transform: rotateY(360deg);
  }
}

3. Load the jQuery JavaScript library by adding the following CDN link before closing the body tag:

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js'></script>

4. Finally, include the following JavaScript function to dynamically animate stars upon user selection.

function rand(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min)
}

function score() {
	let currentScore = $("ul").data('score')
	$('li').each( function(i, e) {
		if (i < currentScore) {
			setTimeout(() => {
				e.classList.remove('off')
				spark(e, 5*i, i*50, i*20)
			}, i*50)
		} else {
			e.classList.add('off')
		}
	})
}

function setScore(s) {
	if ($("ul").data('score') == s) {
		$("ul").data('score', 0)
	} else {
		$("ul").data('score', s)
	}
	score()
}

function spark(e, nbStars, amp = 50, delay = 200) {
	const possibleStars = ["✨", "⭐", "🌟", "💫"]
	
		for (let i = 0; i < nbStars; i++) {
		let s = document.createElement('span');
		s.textContent = possibleStars[rand(0,possibleStars.length-1)];
		s.style.setProperty('--t', rand(-amp, amp) + "%");
		s.style.setProperty('--l', rand(-amp, amp) + "%");
		s.style.setProperty('--d', rand(0, delay) + "ms");
		e.append(s);
		setTimeout(() => { s.remove() }, 3000);
	}
}

$("li").on( "mouseenter", function() {
	spark($(this), 2)
})

score()

That’s all! hopefully, you have successfully created a dynamic star rating. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X