star-rating-svg
by tomik23
HTML
<div class="container">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="star-full" viewBox="0 0 32 32">
<path d="M32 12.408l-11.056-1.607L16 .783l-4.944 10.018L0 12.408l8 7.798-1.889 11.011L16 26.018l9.889 5.199L24 20.206l8-7.798z" />
</symbol>
<symbol id="star-half" viewBox="0 0 32 32">
<path d="M32 12.408l-11.056-1.607L16 .783l-4.944 10.018L0 12.408l8 7.798-1.889 11.011L16 26.018l9.889 5.199L24 20.206l8-7.798zM16 23.547l-.029.015L16 5.725l3.492 7.075 7.807 1.134-5.65 5.507 1.334 7.776L16 23.546z" />
</symbol>
<symbol id="star-empty" viewBox="0 0 32 32">
<path d="M32 12.408l-11.056-1.607L16 .783l-4.944 10.018L0 12.408l8 7.798-1.889 11.011L16 26.018l9.889 5.199L24 20.206l8-7.798zM16 23.547l-6.983 3.671 1.334-7.776-5.65-5.507 7.808-1.134 3.492-7.075 3.492 7.075 7.807 1.134-5.65 5.507 1.334 7.776-6.983-3.671z" />
</symbol>
</svg>
<!-- <svg class="icon">
<use xlink:href="#star-full">
</svg>
<svg class="icon">
<use xlink:href="#star-half">
</svg> -->
<div class="star-box">
<div class="stars">
<a href="#" class="star"><svg class="icon">
<use xlink:href="#star-full">
</svg>
</a>
<a href="#" class="star"><svg class="icon">
<use xlink:href="#star-full">
</svg>
</a>
<a href="#" class="star"><svg class="icon">
<use xlink:href="#star-full">
</svg>
</a>
<a href="#" class="star"><svg class="icon">
<use xlink:href="#star-full">
</svg>
</a>
<a href="#" class="star"><svg class="icon">
<use xlink:href="#star-full">
</svg>
</a>
</div>
<div class="rated"></div>
</div>
</div>
CSS
*,
:after,
:before {
box-sizing: border-box;
}
html {
height: 100%;
}
body {
height: 100%;
min-height: 100%;
background-color: #dadada;
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif
}
svg {
max-height: 100%;
fill: white;
pointer-events: none;
}
svg:not(:root) {
overflow: hidden;
}
.icon {
max-width: 52px;
max-height: 52px;
margin: 5px;
}
.stars {
display: flex;
flex-flow: row-reverse;
justify-content: flex-end;
}
.star.is-selected svg,
.star.is-selected~.star svg {
fill: #ff7300;
}
.star:hover svg,
.star:hover~.star svg {
fill: #ffa500;
}
.container {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.rated {
text-align: center;
}
JavaScript
const starContainer = document.querySelector('.stars');
const stars = [...starContainer.children];
const totalStars = stars.length;
const rated = document.querySelector('.rated');
starContainer.addEventListener('click', (e) => {
console.log(stars);
const index = stars.indexOf(e.target);
const count = totalStars - index;
stars.forEach(el => el.classList.remove('is-selected'));
e.target.classList.add('is-selected');
rated.textContent = `You have rated ${count} stars`;
});