Bootstrap star rating with bootstrap 4+

By | February 4, 2020
Rate this post

I wanted to use star rating available out of the box from bootstrap. I stumbled upon this link and started using this readily only to find that this does not work with bootstrap 4. So like any developer does, looked into the source code and modified JQuery Plugin to make this work. 

This bootstrap plugin is based on glyphicon’s which as we know are deprecated in bootstrap 4+. So really what we need to do is, modify the calling function to replace them with font-awesome star icon ex: fa -fa-star. Plugin is smart enough to take your changes and use font-awesome library instead. 

I have added a snippet of JQuery function. 


$('#star-rating-value').rating({
min: 0,
max: 100,
step: 20,
size: 'lg',
showClear: false,
filledStar: '<i class="fa fa-star" ></i>',
emptyStar: '<i class="fa fa-star"></i>'
});

 

Bonus points: You can modify out of box functionality by simply overriding the existing jQuery function. For example, I want star to display different types of labels instead of 1-5, I want 0-100. 

Below snippet allows you to override any JQuery function

(function ($) {
   var originalVal = $.fn.ratingLocales.en;
   $.fn.ratingLocales.en = {
   defaultCaption: '{rating} Stars',
   starCaptions: {
        20: 'One Star',
        40: 'Two Stars',
        60: 'Three Stars',
        80: 'Four Stars',
       100: 'Five Stars'
   },
  clearButtonTitle: 'Clear',
  clearCaption: ''
 };
  return originalVal;
})(jQuery);

In this scenario, the function name cannot change, it should be same as defined in bootstrap plugin

I hope you enjoyed reading this little tip!