JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Star Rating With Javascript</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" id="container">
<div class="rating" >2</div>
<div class="rating" >3.2</div>
<div class="rating" >4.8</div>
<div class="rating" >5.0</div>
<div class="rating" >2.6</div>
</div>
<script src="stars.js"></script>
</body>
</html>
CSS
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
.container{
margin: 10rem auto;
width: 100px;
}
.ratingsContainer{
display: flex;
min-height: 1.5rem;
justify-content: space-between;
align-items: center;
max-width: 100%;
}
.starContainer{
width: 1rem;
height: 1rem;
position: relative;
}
.starFill{
overflow: hidden;
}
.starOutline{
width: 1rem;
height: 1rem;
position: absolute;
top: 0;
}
.starFill img{
width: 1rem;
height: 1rem;
}
.starOutline img{
width: 1rem;
height: 1rem;
}
JavaScript
//get the parent div (.container)
const ratingsContainer = document.getElementById('container');
//get all the ratings on the page so we cn iterate through them
const ratings = ratingsContainer.getElementsByClassName('rating');
let newRatingsContainer;
function generateStars(percentageFill) {
const newstarContainer = document.createElement('div');
newstarContainer.className = 'starContainer';
const starFill = document.createElement('div');
starFill.className = 'starFill';
starFill.style.width = `${percentageFill}%`;
const starFillImage = document.createElement('img');
starFillImage.src = 'https://marchv.net/images/star.svg';
const starOutline = document.createElement('div');
starOutline.className = 'starOutline';
const starOutlineImage = document.createElement('img');
starOutlineImage.src = 'https://marchv.net/images/outline.svg';
newstarContainer.appendChild(starFill).appendChild(starFillImage);
newstarContainer.appendChild(starOutline).appendChild(starOutlineImage);
document
.getElementById('container')
.appendChild(newRatingsContainer)
.appendChild(newstarContainer);
}
//iterate through all divs with ratings class in the container element
for (let i = 0; i < ratings.length; i++) {
//get the number rating from each div and make sure its a float with one decimal poiint
const ratingScore = parseFloat(ratings[i].textContent).toFixed(1);
//get the full stars required
const fullStars = Math.floor(ratingScore);
//get the fractional stars required
const fractionalStarsFill = ratingScore.split('.')[1] * 10;
//get the left over stars (empty stars).
let emptyStars;
emptyStars = fractionalStarsFill > 0 ? 4 - fullStars : 5 - fullStars;
//generate ratings container div
newRatingsContainer = document.createElement('div');
newRatingsContainer.className = 'ratingsContainer';
//add full stars to ratings container
for (let i = 0; i < fullStars; i++) {
generateStars(100);
}
//add...