CSS Rating System
Allows the user hover for a 5 star rating. CSS only.
(For actual use a JS click event needs to be attached and CSS added to correctly display after the user has voted.)
HTML
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="rating">
<span class="stars-container">
<span id="star5" class="fa star"></span>
<span id="star4" class="fa star"></span>
<span id="star3" class="fa star"></span>
<span id="star2" class="fa star"></span>
<span id="star1" class="fa star"></span>
</span>
<a class="reviews">(40)</a>
</div>
<button>Reset Stars</button>
CSS
/* set all stars to 'empty star' */
.stars-container {
display: inline-block;
vertical-align: top;
}
/* set all stars to 'empty star' */
.stars-container .star {
float: right;
display: inline-block;
padding: 2px;
color: orange;
cursor: pointer;
}
.stars-container .star:before {
content:"\f006";
/* fontAwesome empty star code */
}
/* set hovered/selected star to 'filled star' */
.star:hover:before, .star.selected:before {
content:"\f005";
/* fontAwesome filled star code */
}
/* set all stars after hovered/selected to'filled star'
** it will appear that it selects all after due to positioning */
.star:hover ~ .star:before, .star.selected ~ .star:before {
content:"\f005";
/* fontAwesome filled star code */
}
.reviews {
vertical-align: top;
}
button {
margin-top: 20px;
}
JavaScript
/* Prototype code for Rating System */
var numReviews = 40; //example, this data would not likely be hardcoded
// basic click event sets selected class
$('.star').on('click', function () {
resetStars();
//add select class
$(this).addClass('selected');
numReviews++; //example, this data would not likely be hardcoded
updateReviewNum();
});
// reset for demo
$('button').on('click', function () {
resetStars();
//add select class
$(this).addClass('selected');
numReviews = 40; //example, this data would not likely be hardcoded
updateReviewNum();
});
function resetStars() {
//resets stars by removing selected class
$('.star').removeClass('selected');
}
function updateReviewNum() {
//example, in real life - update via ajax, get response, update UI
$('.reviews').text('(' + numReviews + ')');
}