Skip to content

Instantly share code, notes, and snippets.

@kkasaei
Created November 27, 2023 11:30
Show Gist options
  • Save kkasaei/8f7db14ca64bff19b52a9a4372e65926 to your computer and use it in GitHub Desktop.
Save kkasaei/8f7db14ca64bff19b52a9a4372e65926 to your computer and use it in GitHub Desktop.
Image Sprites
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stars</title>
<style>
.star,
.half-star,
.empty-star {
background-repeat: no-repeat;
background-image: url('./stars.png');
}
.star {
height: 100px;
width: 104.57px;
background-position: 0 0;
}
.empty-star {
height: 100px;
width: 104.57px;
background-position: -104.57px 0;
}
.half-star {
height: 100px;
width: 104.57px;
background-position: -209.14px 0;
}
.stars {
display: flex;
}
</style>
</head>
<body>
<script>
const data = [5]
const star = document.querySelector('.star')
// create a function to take the data and create the stars out of 5 stars
function createStars(data) {
// create a variable to store the stars
let stars = ''
// loop through the data
data.forEach((item) => {
// create a variable to store the stars
let star = ''
// create a variable to store the empty stars
let emptyStar = ''
// create a variable to store the half stars
let halfStar = ''
// create a variable to store the number of stars
let numberOfStars = Math.floor(item)
// create a variable to store the number of empty stars
let numberOfEmptyStars = 5 - numberOfStars
// create a variable to store the number of half stars
let numberOfHalfStars = item - numberOfStars
// If the total number if greater than 5 remove 1
if (numberOfStars + numberOfHalfStars + numberOfEmptyStars > 5) {
numberOfEmptyStars -= 1
}
// loop through the number of stars
for (let i = 0; i < numberOfStars; i++) {
// add a star to the star variable
star += `<div class="star"></div>`
}
// loop through the number of empty stars
for (let i = 0; i < numberOfEmptyStars; i++) {
// add an empty star to the empty star variable
emptyStar += `<div class="empty-star"></div>`
}
// loop through the number of half stars
for (let i = 0; i < numberOfHalfStars; i++) {
// add a half star to the half star variable
halfStar += `<div class="half-star"></div>`
}
// add the stars to the stars variable
stars += `<div class="stars">${star}${halfStar}${emptyStar}</div>`
})
// return the stars
return stars
}
// Invoke the function
// createStars(data)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment