dev4web
2/24/2016 - 8:16 PM

Star rating

Star rating

.rating {
	cursor: pointer;
}

.rating .rating-star {
	display: inline-block;
  position: relative;
  padding-right: 5px;
  margin-left: -5px;
  color: #e3cf7a;
}
.rating .selected:before {
  content: '\f005';
}
$(document).ready(function () {
  $('.rating-star')
  .on('mouseover', function(e) {
    var rating = $(e.target).data('rating');
    // fill all the stars
    $('.rating-star').removeClass('fa-star-o').addClass('fa-star');
    // empty all the stars to the right of the mouse
    $('.rating-star#rating-' + rating + ' ~ .rating-star').removeClass('fa-star').addClass('fa-star-o');
  })
  .on('mouseleave', function (e) {
    // empty all the stars except those with class .selected
    $('.rating-star').removeClass('fa-star').addClass('fa-star-o');
  })
  .on('click', function(e) {
    var rating = $(e.target).data('rating');
    $('#rating-input').val(rating);
    // fill all the stars assigning the '.selected' class
    $('.rating-star').removeClass('fa-star-o').addClass('selected');
    // empty all the stars to the right of the mouse
    $('.rating-star#rating-' + rating + ' ~ .rating-star').removeClass('selected').addClass('fa-star-o');
  })
});
<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link data-require="fontawesome@*" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Rate whatever you want</h1>
    <form>
      <!-- hide the input -->  
      <input type="number" name="rating" id="rating-input" min="1" max="5" />
    </form>
    
    <div class="rating">
      <!-- in Rails just use 1.upto(5) -->  
      <i class="fa fa-star-o fa-2x rating-star" id="rating-1" data-rating="1"></i>
      <i class="fa fa-star-o fa-2x rating-star" id="rating-2" data-rating="2"></i>
      <i class="fa fa-star-o fa-2x rating-star" id="rating-3" data-rating="3"></i>
      <i class="fa fa-star-o fa-2x rating-star" id="rating-4" data-rating="4"></i>
      <i class="fa fa-star-o fa-2x rating-star" id="rating-5" data-rating="5"></i>
    </div>
  </body>

</html>

Star rating

JQuery + CSS code to make a simple rating widget based on Fontawesome. Nothing fancy but I don't want to figure out how to do it again.

Based on the example found here: http://css-tricks.com/star-ratings/ which unfortunately provides only CSS and no actual functionality.

See it on Plunker: https://plnkr.co/vptHYAnWHMbX2LfR6a02