JSFiddle - React, Tailwind, and code Playground
by Alexandru Gatea
HTML
<h1>Star Rating | <span class="selected-stars">You have choosen <span>0</span> stars.</span>
</h1>
<div class="star-rating">
<!-- first star -->
<div class="star">
<input type="radio" name="star" value="1">
<span>★</span>
<!-- second star -->
<div class="star">
<input type="radio" name="star" value="2">
<span>★</span>
<!-- third star -->
<div class="star">
<input type="radio" name="star" value="3">
<span>★</span>
<!-- fourth star -->
<div class="star">
<input type="radio" name="star" value="4">
<span>★</span>
<!-- fifth star -->
<div class="star">
<input type="radio" name="star" value="5">
<span>★</span>
</div>
</div>
</div>
</div>
</div>
</div>
<br><br>
SCSS
h1 {
padding: 30px 10px;
}
.star-rating {
display: inline-flex;
.star {
font-size: 3rem;
cursor: pointer;
display: flex;
position: relative;
padding: 0 10px;
}
}
input {
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.star {
color: black;
}
.star:hover {
color: orange;
}
.is-selected:not(.hover) {
.star {
color: orange;
&:hover span {
color: orange;
}
}
.star input[type="radio"]:checked+span+.star span {
color: black;
}
}
JavaScript
$('.star-rating')
.on('click', function() {
$(this).addClass('is-selected');
})
.hover(
function() {
$(this).addClass('hover')
},
function() {
$(this).removeClass('hover')
})
$('input').on('click', function() {
$('.selected-stars span').text($(this).val())
});