Bootstrap Star Rating bootstrap-star-rating

Thankful to Krajee!
to get more out of us.

NOTE: The plugins on this site, strive to use a lot of CSS3 and HTML5 features in addition to JQuery. Hence, one may find either CSS3, HTML5 or a mix of both to achieve a plugin's requirements in many implementations.

A simple yet powerful JQuery star rating plugin for Bootstrap which supports advanced features like fractional star fill and RTL input support. Developed with a focus on utlizing pure CSS-3 styling to render the control. The plugin uses Bootstrap markup and styling by default, but it can be overridden with any other CSS markup. View a complete demo.

NOTE

Version 4.0.0 has been released. Release 4.0.0 is a modified rewrite with various new enhancements and BC breaking features. Refer change log for new features and details.

  • Convert any HTML input to a star rating control.

  • Easy Configuration: The plugin automatically converts an input to a star rating control if you set its class = rating. All options to the input can be passed as HTML5 data attributes.

  • The plugin supports fractional star ratings. So one can have any fractional stars highlighted and managed. This is totally configurable and one of a significant differentiator as compared to most other rating plugins.

  • Ability to size the rating control to any size including the stars, caption, and clear button. Five prebuilt size templates are available xl, lg, md, sm, and xs. However one can have their own size configured through a simple CSS manipulation.

  • Use any of your favorite font icon frameworks to render your star symbols (for example you can easily use the icons from the FontAwesome library).

  • The plugin supports themes for advanced styling.

  • The plugin includes translation and locale support for multi languages.

  • You can use the HTML 5 number input for polyfill and the plugin will automatically use the number attributes like min, max, and step. However, number inputs have a problem with decimal values on the Chrome Browser. Read the Browser Support section below.

  • Involves pure CSS3 styling of the stars. Say goodbye to image sprites or playing with image backgrounds. Offers clean scalable vector icons for consistent display across devices.

  • Specifically uses Bootstrap 3.x styles & glyphs. Can be combined to work better for Bootstrap styled projects (or input group addons).

  • Ability to clear values and options for the stars. Control where the clear button element can be shown.

  • Reset star rating to the initial value when the form is reset.

  • Ability to control and display caption of the selected stars. Each rated star can have its own caption. Control where the caption element can be shown.

  • Support for RIGHT TO LEFT (RTL) input. Automatically changes star styling for RTL.

  • Triggers JQuery events for advanced development. Events currently available are rating.change, rating.clear, and rating.reset.

  • Disabled and readonly input star rating support.

  • Change stars and caption on mouse hover (new feature since v3.0.0).

  • Change stars and caption on slide and drag for mobile/touch devices (new feature since v3.1.0).

Note: Release 4.0.0 is a modified rewrite with various new enhancements and BC breaking features.
  • BC Breaking Changes: The symbol and glyphicon properties have been be removed. The functionality is replaced with the theme property (and can also be complemented or implemented separately using the containerClass property).

  • New property theme will assign a CSS class with the rating- to the rating container. Themes included with the plugin:

    • '' (blank) the default theme (for displaying bootstrap GLYPHICONS)

    • krajee-svg (for displaying SVG icons)

    • krajee-uni (for displaying UNICODE symbols as stars)

    • krajee-fa (for displaying FONT AWESOME icons)

  • Add ability to override and add one's own themes.

  • Stars now have a better padding and spacing that can be configured via CSS and themes.

  • New property filledStar that will allow one to set the markup for filledStar. This defaults to <i class="glyphicon glyphicon-star"></i>. Note that unlike earlier releases no symbol is needed anymore. One can setup a HTML markup here and can thus achieve richer/complex markup for displaying their stars.

  • New property emptyStar that will allow one to set the markup for emptyStar. This defaults to <i class="glyphicon glyphicon-star-empty"></i>. Note that unlike earlier releases no symbol is needed anymore. One can setup a HTML markup here and can thus achieve richer/complex markup for displaying their stars.

  • Exclusive support for SVG (and a prebuilt krajee-svg theme that contains two different ready to use SVG icons).

  • Ability to easily set the widget as a "display only" rating via displayOnly property.

  • New property animate to control animation of highlighted stars on hover or click.

Browser Support

If you are using the HTML5 NUMBER input to initialize the rating, please read this. The number field does not accept decimals in Google Chrome. The input is allowed, but when the user submits the form, they get an error message and are instructed to enter a valid number (whole numbers only). Other browsers like Firefox allow decimals on the number fields. Till this is standardized across browsers, the workaround for this is to use a normal text input, and initialize the rating via javascript.

Note

  • When using the rtl mode, you must ensure that the icon markup you set in filledStar is symmetrical horizontally. This is because the plugin default CSS styling uses a horizontal mirror flipped version of the filledStar markup.

  • The rtl input ratings are by default floated right. You may need to add a <div class="clearfix></div> for bootstrap styling after RTL ratings to ensure that floats are cleared for subsequent content displayed.

  • If you are already using a HTML markup on your page which has the content RTL oriented, then you must be careful in setting the rtl property. For example, if you have an <html dir="rtl"> at top of your page and wish to have a RTL oriented star rating, then you may take one of the following approaches to render a proper RTL rating

    • Option 1: Wrap the rating inside a LTR container e.g. <div dir="ltr">.

    • Option 2: You can set the rtl setting for the plugin to false.

  1. Latest JQuery

  2. Most modern browsers supporting CSS3, HTML5 inputs, & JQuery. For Internet Explorer, one must use IE versions 9 and above to render the rating.

  3. Bootstrap 3.x is optional and used by default, but can be overridden to use any CSS.

The plugin can be installed automatically or manually using one of these options:

Bower Package Manager

Installation via bower package manager is as simple as running:
$ bower install bootstrap-star-rating

Composer Package Manager

You can install bootstrap star rating via composer package manager. Either run

$ php composer.phar require kartik-v/bootstrap-star-rating "@dev"

or add:

"kartik-v/bootstrap-star-rating": "@dev"

to your composer.json file

Manual Install

You can also manually install the plugin easily to your project. Just download the source ZIP or TAR ball and extract the plugin assets (css and js folders) into your project.

Note

The plugin will automatically convert fields of [input class="rating"] to a star rating control, i.e. if you attach a css class rating to the input. But, if you are initializing the plugin separately via javascript, then DO NOT ATTACH the css class rating to the input (as it will result in duplicate initializations and the javascript code maybe skipped).

Step 1: Load the following assets in your header.

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
<link href="path/to/css/star-rating.css" media="all" rel="stylesheet" type="text/css" />

<!-- optionally if you need to use a theme, then include the theme file as mentioned below -->
<link href="path/to/themes/krajee-svg/theme.css" media="all" rel="stylesheet" type="text/css" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script src="path/to/js/star-rating.js" type="text/javascript"></script>

<!-- optionally if you need to use a theme, then include the theme file as mentioned below -->
<script src="path/to/themes/krajee-svg/theme.js"></script>

<!-- optionally if you need translation for your language then include locale file as mentioned below -->
<script src="path/to/js/locales/{lang}.js"></script>

If you noticed, you need to load the jquery.min.js and bootstrap.min.css in addition to the star-rating.min.css and star-rating.min.js. The theme files and translation files are optional addons.

Step 2a: Initialize the plugin on your page. For example,

// initialize with defaults
$("#input-id").rating();
 
// with plugin options
$("#input-id").rating({min:1, max:10, step:2, size:'lg'});

The #input-id is the identifier for the input on your page, which is hidden automatically by the plugin.

Step 2b: Alternatively, you can directly set the plugin options to any input, through HTML 5 data attributes to your input field.

<input id="input-id" name="input-name" type="number" class="rating" min=1 max=10 step=2 data-size="lg" data-rtl="true">

As shown in the usage section, translations are now enabled with release 3.5.5. You can load a locale file /star-rating_locale_<lang>.js after the core star-rating.min.js file, where <lang> is the language code (e.g. de, fr etc.). If locale file does not exist, you can submit a translation for the new language via a new pull request to add to this folder. Check the sample locale file to copy and create a translation configuration for your own language.

The plugin supports these following options:

language

string language configuration for the plugin to enable the plugin to display messages for your locale (you must set the ISO code for the language). You can have multiple language widgets on the same page. The locale JS file for the language code must be defined as mentioned in the translations section. The file must be loaded after star-rating.js.

containerClass

string the CSS class to be appended to the star rating container. This is useful if you want to prefix some CSS class to the container and override the plugin widget styling for your use case. This can be used in conjunction with theme property also if needed. Defaults to an empty string ''.

theme

string the theme to be applied for the rating. Defaults to a blank string ''. If a value is set here, the plugin will automatically append the CSS 'theme-{name}' to the containerClass, where {name} will be replaced with this theme property setting. You can build your own theme CSS file based on theme setting and need to load the theme specific CSS file after bootstrap.css.

The following themes are provided inbuilt with the plugin:

  • '' (blank) the default theme (for displaying bootstrap GLYPHICONS). No additional CSS file is needed to be loaded other than the default star-rating.css.

  • krajee-svg (for displaying SVG icons). To use this theme, you must set theme property to krajee-svg and additionally load the theme CSS file theme-krajee-svg.css from the plugin CSS folder (after the default star-rating.css).

  • krajee-uni (for displaying UNICODE symbols as stars). To use this theme, you must set theme property to krajee-uni and additionally load the theme CSS file theme-krajee-uni.css from the plugin CSS folder (after the default star-rating.css).

  • krajee-fa (for displaying FONT AWESOME icons). To use this theme, you must set theme property to krajee-fa and additionally load the theme CSS file theme-krajee-fa.css from the plugin CSS folder (after the default star-rating.css).

emptyStar

string the symbol markup to display for an empty star. Note that unlike earlier releases, you can set a HTML markup to render the star. Defaults to:

  • <i class="glyphicon glyphicon-star-empty"></i>

filledStar

string the symbol markup to display for a filled / highlighted star. Note that unlike earlier releases, you can set a HTML markup to render the star. Defaults to:

  • <i class="glyphicon glyphicon-star"></i>

stars

int the number of stars to display. Defaults to 5.

min

float the minimum value for the rating input. Defaults to 0. Note that this is the lowest rating value when no stars are selected or highlighted.

max

float the maximum value for the rating input. Defaults to 5. Note that this is the highest rating value when all stars are selected or highlighted.

step

float the step to increment the rating when each star is clicked. Defaults to 0.5.

Star Highlight Logic

The logic for highlighting stars depends on the stars, min, max, and step configurations. The percentage of each star to be highlighted for each step, will be evaluated using the following expression:

STAR_HIGHLIGHT_PERCENT = (max - min) * step * 100 / stars
For example:
  1. If min = 0, max = 5, step = 0.5, and stars = 5, then STAR_HIGHLIGHT_PERCENT will evaluate to 50% of each star for each step.

  2. If min = 1, max = 5, step = 0.5, and stars = 5, then STAR_HIGHLIGHT_PERCENT will evaluate to 40% of each star for each step.

So, for example 2 above, the stars will not be completely highlighted as desired. It is therefore important you set the configuration of stars, min, max, and step correctly.

disabled

boolean whether the input is disabled. Defaults to false.

readonly

boolean whether the input is read only. Defaults to false.

displayOnly

boolean whether the widget is a display only control. This is a bit different than disabled and readonly. It actually provides a fast shortcut method, to only display a rating with highlighted stars in a view and hides the caption and clear button. It also prevent any edits to the rating control by the user (but can be edited via javascript).

rtl

boolean whether the rating input is to be oriented RIGHT TO LEFT. Defaults to false.

Note

  • When using the rtl mode, you must ensure that the icon markup you set in filledStar is symmetrical horizontally. This is because the plugin default CSS styling uses a horizontal mirror flipped version of the filledStar markup.

  • The rtl input ratings are by default floated right. You may need to add a <div class="clearfix></div> for bootstrap styling after RTL ratings to ensure that floats are cleared for subsequent content displayed.

  • If you are already using a HTML markup on your page which has the content RTL oriented, then you must be careful in setting the rtl property. For example, if you have an <html dir="rtl"> at top of your page and wish to have a RTL oriented star rating, then you may take one of the following approaches to render a proper RTL rating

    • Option 1: Wrap the rating inside a LTR container e.g. <div dir="ltr">.

    • Option 2: You can set the rtl setting for the plugin to false.

animate

boolean whether to animate the stars when the rating stars are highlighted on hover or click. Defaults to true.

showClear

boolean whether the clear button is to be displayed. Defaults to true.

showCaption

boolean whether the rating caption is to be displayed. Defaults to true.

size

string size of the rating control. One of xl, lg, md, sm, or xs. Defaults to md.

defaultCaption

string the default caption text, which will be displayed when no caption is setup for the rating in the starCaptions array. This variable defaults to {rating} Stars, where the variable {rating} will be replaced with the selected star rating.

starCaptions

array | function the caption titles corresponding to each of the star rating selected. Defaults to

{
    0.5: 'Half Star',
    1: 'One Star',
    1.5: 'One & Half Star',
    2: 'Two Stars',
    2.5: 'Two & Half Stars',
    3: 'Three Stars',
    3.5: 'Three & Half Stars',
    4: 'Four Stars',
    4.5: 'Four & Half Stars',
    5: 'Five Stars'
}

This can also be configured as a function that returns a star caption based on a supplied parameter val, where val is the calculated rating. For example:

starCaptions: function(val) {
    if (val < 3) {
        return 'Low: ' + val + ' stars';
    } else {
        return 'High: ' + val + ' stars';
    }
}

Note

If starCaptions is set as an object, the data will be merged with the default values. If you want to override the default entirely, you need to override all values in the object, OR setup this as a function callback.

starCaptionClasses

array | function the caption css classes corresponding to each of the star rating selected. Defaults to

{
    0.5: 'label label-danger',
    1: 'label label-danger',
    1.5: 'label label-warning',
    2: 'label label-warning',
    2.5: 'label label-info',
    3: 'label label-info',
    3.5: 'label label-primary',
    4: 'label label-primary',
    4.5: 'label label-success',
    5: 'label label-success'
}

This can also be configured as a function that returns a star caption based on a supplied parameter val, where val is the calculated rating. For example:

starCaptionClasses: function(val) {
    if (val == 0) {
       return 'label label-default';
    }
    else if (val < 3) {
        return 'label label-danger';
    } 
    else {
        return 'label label-success';
    }
}

Note

If starCaptionClasses is set as an object, the data will be merged with the default values. If you want to override the default entirely, you need to override all values in the object, OR setup this as a function callback.

clearButton

string the markup for displaying the clear button. Defaults to <i class="glyphicon glyphicon-minus-sign"></i>.

clearButtonTitle

string the title displayed on clear button hover. Defaults to Clear.

clearButtonBaseClass

string the base CSS class for the clear button. Defaults to clear-rating.

clearButtonActiveClass

string the CSS class for the clear button that will be appended to the base class above when button is hovered/activated. Defaults to clear-rating-active.

clearValue

string the value to clear the input to, when the clear button is clicked. Defaults to min if not set.

clearCaption

string the caption displayed when clear button is clicked. Defaults to Not Rated.

clearCaptionClass

string the CSS Class to apply to the caption displayed, when clear button is clicked. Defaults to label label-default.

captionElement

string the identifier for the container element selector for displaying the caption. Defaults to a div container with .caption class inside the rating control.

clearElement

string the identifier for the container element selector for displaying the clear button. Defaults to a div container with .clear-rating class inside the rating control.

hoverEnabled

boolean whether hover functionality is enabled. This will dynamically change the stars and caption on mouse hover. Defaults to true.

Note

The hover functionality will only work on desktop pointing devices and if the input is not disabled or readonly. For all hover functionalities in this plugin (including properties below), the rating state will be reverted back to original if the mouse is exited out without clicking.

hoverChangeCaption

boolean control whether the caption should dynamically change on mouse hover. Defaults to true. Will be applicable only if hoverEnabled is true.

hoverChangeStars

boolean control whether the stars should dynamically change on mouse hover. Defaults to true. Will be applicable only if hoverEnabled is true.

hoverOnClear

boolean whether to dynamically clear the rating on hovering the clear button. Defaults to true. Will be applicable only if hoverEnabled is true.

The plugin supports these events:

rating.change

This event is triggered when the star rating is modified or changed. This event also allows you to access these parameters:

  • value: the selected rating value

  • caption: the caption for the selected rating

Example:

$('#input-id').on('rating.change', function(event, value, caption) {
    console.log(value);
    console.log(caption);
});

rating.clear

This event is triggered when the rating is cleared with the clear button.

Example:

$('#input-id').on('rating.clear', function(event) {
    console.log("rating.clear");
});

rating.reset

This event is triggered when the rating is reset to initial value.

Example:

$('#input-id').on('rating.reset', function(event) {
    console.log("rating.reset");
});

rating.hover

This event is triggered, when the mouse (pointing input device) is hovered inside a star rating or the clear button. This event also allows you to access these parameters:

  • value: the selected rating value

  • caption: the caption for the selected rating

  • target: the target for the hover - returns whether you hovered on the stars or the clear button.

Example:

$('#input-id').on('rating.hover', function(event, value, caption, target) {
    console.log(value);
    console.log(caption);
    console.log(target);
});

rating.hoverleave

This event is triggered, when the mouse (pointing input device) is hovered out of a star rating or the clear button without clicking. This event also allows you to access these parameters:

  • target: the target for the hover - returns whether you left hovering on the stars or the clear button.

$('#input-id').on('rating.hoverleave', function(event, target) {
    console.log(target);
});

The plugin supports the following methods. Many of the methods below support method chaining because they return the file input element as a jQuery object.

update

Update the rating by setting a value via javascript. The method accepts a rating value as a parameter. This method returns the rating input element as a jQuery object and can thus be chained with other methods.

$('#input-id').rating('update', 3);

// method chaining 
var ratingValue = $('#input-id').rating('update', 3).val();

refresh

Use this method to dynamically refresh the rating options via javascript after the plugin has been initialized. The method accepts the plugin options entered as an object (associative array). This method returns the rating input element as a jQuery object and can thus be chained with other methods.

// Example: Call the method below in rating.change event to disable the rating and
// hide the clear button.
$('#input-id').rating('refresh', {disabled: true, showClear: false, showCaption: true});

// method chaining 
var ratingValue = $('#input-id').rating('refresh', {
    disabled: true, 
    showClear: false, 
    showCaption: true
}).val();

reset

Reset the rating to the initial value. For example after a form reset. This method returns the rating input element as a jQuery object and can thus be chained with other methods.

$('#input-id').rating('reset');

// method chaining 
var ratingValue = $('#input-id').rating('reset').val();

clear

Clear the rating. This method returns the rating input element as a jQuery object and can thus be chained with other methods.

$('#input-id').rating('clear');

// method chaining 
var ratingValue = $('#input-id').rating('clear').val();

destroy

Destroys the rating. This method returns the rating input element as a jQuery object and can thus be chained with other methods.

$('#input-id').rating('destroy');

// method chaining 
var ratingValue = $('#input-id').rating('destroy').val();

create

Creates the rating after destroying any existing rating plugin instance. This method returns the rating input element as a jQuery object and can thus be chained with other methods.

// will re-create rating based on initial plugin options
$('#input-id').rating('create');

// method chaining 
var ratingValue = $('#input-id').rating('create').val();

// any new plugin options if passed will be used instead of initial plugin options
$('#input-id').rating('create', {disabled: true});

The plugin has been implemented as extensions in the following frameworks

Sl.FrameworkExtension SourceDeveloped ByExtension Demo
1.Yii Framework 2.0Yii2 WidgetsKrajee Yii2 Star Rating

Do you know any other framework extension using this plugin which is not listed here? Tell us so that we can consider its inclusion in this list.

bootstrap-star-rating is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.