Git Product home page Git Product logo

bootstrap-rating's Introduction

Bootstrap Rating

Bootstrap Rating is a jQuery plugin that creates a rating control that uses Bootstrap glyphicons for rating symbols.

See bootstrap rating in action.

Dependencies

Bootstrap Rating depends on jQuery and can use Bootstrap for the rating symbols. Actually, the glyphs in font format that Bootstrap provides.

<link href="dist/css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="dist/js/jquery-1.10.2.js"></script>

Usage

Bootstrap Rating uses a hidden input to keep the rating value. This value corresponds to the 0-based index of the selected rating.

Any rating input, those with class rating, are implicitly initialized.

<input type="hidden" class="rating"/>

Also it can be explicitly initialized just calling .rating() on the desired input:

$('input').rating();

Behind the rating control

Bootstrap Rating uses an input to keep the rating value. But the relationship between the behind the scenes input control and the rating control goes a little further. This input is the associated control. They are tied together.

You can disable the rating control simply disabling its associated input control:

<input type="hidden" class="rating" disabled="disabled"/>

Make it read only:

<input type="hidden" class="rating" data-readonly/>

Set its initial value:

<input type="hidden" class="rating" value="2"/>

Or attach events:

$('input').on('change', function () {
  alert('Rating: ' + $(this).val());
});

Customizing the rating symbols

The default rating symbols can be replaced with another ones. Just add the desired glyphicon for the filled and empty states:

<input type="hidden" class="rating" data-filled="glyphicon glyphicon-heart" data-empty="glyphicon glyphicon-heart-empty"/>

Check the available glyphs.

Again, you can explicitly initialize the plugin passing the glyphicons as parameters:

$('input').rating({
  filled: 'glyphicon glyphicon-heart',
  empty: 'glyphicon glyphicon-heart-empty'
});

If you want to change the default glyphicons for all the rating controls, you only need to override the plugin default values:

$.fn.rating.defaults.filled = 'glyphicon glyphicon-heart';
$.fn.rating.defaults.empty = 'glyphicon glyphicon-heart-empty';

This needs only be called once, but remember to make these assignments before the rating controls are created.

If you even want more control over the symbols appearance, you can customize the selected symbol filled state with the filled-selected attribute. This attribute takes precedence over the default filled state allowing you, for example, to fill only the selected one:

<input type="hidden" class="rating" data-filled="glyphicon glyphicon-heart-empty" data-filled-selected="glyphicon glyphicon-heart" data-empty="glyphicon glyphicon-heart-empty"/>

Or programmatically:

$('input').rating({
  filled: 'glyphicon glyphicon-heart-empty',
  filledSelected: 'glyphicon glyphicon-heart',
  empty: 'glyphicon glyphicon-heart-empty'
});

Using Non-Bootsrap icons

Though the original idea was to use glyphicons provided by Bootstrap, any symbol can be used. It means that the rating control is not tightly tied to Bootstrap and you can use it without Bootstrap.

Font Awesome icons

You can use the Font Awesome by Dave Gandy - http://fontawesome.io. Check Font Awesome for a list of available icons.

  1. Include in the <head> the reference to the Font Awesome CSS.

     <link rel="stylesheet" href="path/to/font-awesome.min.css">
    
  2. Start using the classes provided by Font Awesome.

     <input type="hidden" class="rating" data-filled="fa fa-bell fa-3x" data-empty="fa fa-bell-o fa-3x"/>
    

Custom CSS icons

You can even create your own not font based icons, using raw CSS:

  1. Define a symbol class for empty and filled states.

     .symbol {
       display: inline-block;
       border-radius: 50%;
       border: 5px double white;
       width: 30px;
       height: 30px;
     }
    
     .symbol-empty {
       background-color: #ccc;
     }
    
     .symbol-filled {
       background-color: black;
     }
    
  2. Start using those custom classes.

     <input type="hidden" class="rating" data-filled="symbol symbol-filled" data-empty="symbol symbol-empty"/>
    

Setting rate range

The default range is (0..5], or in plain text, starting at 0 (not included) and stopping at 5 (included). In this case the range of whole symbols would include [1, 2, 3, 4, 5].

It can be overriden by means of two data attributes, data-start for the start rate value and data-stop for the stop/end one. If you want to define a range (5..10]:

<input type="hidden" class="rating" data-start="5" data-stop="10"/>

Also you can explicitly initialize the plugin passing the start and stop values as parameters:

$('input').rating({
  start: 5,
  stop: 10
});

If what you need is to change the default start and stop values for all the rating controls, just override the plugin defaults:

$.fn.rating.defaults.start = 5;
$.fn.rating.defaults.stop = 10;

Fractional range

You can configure the rating to get partial or fractional rates. The data-fractions indicates the number of equal parts that make up a whole symbol.

For example, a data-fractions of two will create a rating with half symbols:

<input type="hidden" class="rating" data-fractions="2"/>

The possible values in this case would be all the whole and half rates between (0..5], i.e, [0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5].

Stepping different

The rating range spans all the integers from start to stop, incremented or decremented by a step. The default step is 1.

Use data-step attribute to change the stepping:

<input type="hidden" class="rating" data-stop="10" data-step="2"/>

Or the explicit initialization:

$('input').rating({
  stop: 10,
  step: 2
});

The range of whole symbols defined in this case would include [2, 4, 6, 8, 10].

Also, as usual, you can change the default step globally:

$.fn.rating.defaults.step = 2

My Python background wouldn't forgive me not supporting negative stepping:

<input type="hidden" class="rating" data-stop="-10" data-step="-2"/>

Giving [-2, -4, -6, -8, -10] as the range of whole symbols.

Getting more control over the symbols

Every time a rating symbol is created the extendSymbol callback is called. This callback gives you the full control over the symbol elements. As with any regular element, you can bind event handlers, add attributes, add classes, or anything you need to customize it. The callback's context is the rating symbol DOM element and receives the rate as parameter.

For example, you could bind the bootstrap tooltip on all the rating symbols to show the rate on hover:

$('input').rating({
  extendSymbol: function (rate) {
    $(this).tooltip({
      container: 'body',
      placement: 'bottom',
      title: 'Rate ' + rate
    });
  }
});

Symbol events

Rating symbols can fire two events rating.rateenter and rate.rateleave. These events are triggered when the pointer enters and leaves a rate.

For example, you can use these events to dynamically update the bootstrap tooltip, even for fractional ratings.

<input type="hidden" class="rating-tooltip-manual" data-filled="fa fa-star fa-3x" data-empty="fa fa-star-o fa-3x" data-fractions="3"/>

$('.rating-tooltip-manual').rating({
  extendSymbol: function () {
    var title;
    $(this).tooltip({
      container: 'body',
      placement: 'bottom',
      trigger: 'manual',
      title: function () {
        return title;
      }
    });
    $(this).on('rating.rateenter', function (e, rate) {
      title = rate;
      $(this).tooltip('show');
    })
    .on('rating.rateleave', function () {
      $(this).tooltip('hide');
    });
  }
});

Methods

rate

You can programmatically set, get, or reset the current rating value via javascript using the rate method.

To set the rate value:

$('input').rating('rate', 2.5);

To get the rate value:

var rate = $('input').rating('rate');

To reset the rate value:

$('input').rating('rate', '');

bootstrap-rating's People

Contributors

dreyescat avatar syone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootstrap-rating's Issues

Interesting behavior in Safari with FA5

Hi, I just found this and am excited to use it. Thanks for creating it.

I found what seems to be an interesting issue when using safari, Bootstrap 4, Font Awesome 5 and JQuery 3.2.1

https://use.fontawesome.com/releases/v5.0.6/js/all.js

Tested in Chrome, looks as expected:
screen shot 2018-03-29 at 11 35 54 am

In Safari (latest), the filled stars drop down to the next line leaving blank space where the empty star was.
screen shot 2018-03-29 at 11 34 22 am

Code:

<div class="col-md-4">
    <h5 class="text-center">Rate:</h5>
<input type="hidden" class="rating" data-filled="fas fa-star fa-2x" data-empty="far fa-star fa-2x" data-fractions="2"/>
</div>

How to re-call .rating() function on new DOM elements with Vue.JS

I have a problem. I'm using Vue.js and Laravel to paginate. I have Vue.js code:

new Vue({
            el: '.container',
            data: {
                reviews: [],
                pagination: {}
            },
            created: function () {
                this.fetchStories();
            },
            methods: {
                fetchStories: function (page_url) {
                    let vm = this;
                    page_url = page_url || '{{ route('admin.products.get-all-reviews') }}';
                    this.$http.get(page_url)
                        .then(function (response) {
                            vm.makePagination(response.data);
                            vm.reviews = response.data.data;
                        }).then(function () {
                            $('.container').find('.all-reviews-rating').rating();
                        });
                },
                makePagination: function(data){
                    let pagination = {
                        current_page: data.current_page,
                        last_page: data.last_page,
                        next_page_url: data.next_page_url,
                        prev_page_url: data.prev_page_url
                    };
                    this.pagination = pagination;
                }
            }
        });

I'm calling $('.container').find('.all-reviews-rating').rating(); after fetching data, but when I get second page it leaves first element's value to second page:

First Page:
image

Second Page:
image

As you can see. On the second page I have 1 star but it get's 5 stars. In HTML in input value it displays correctly.

Is it possible to use images to redefine the symbols?

Hi, is it possible to redefine the rating symbols in the following way?
I have tried, but it looks quite ugly...

css

.symbol-empty {
background-image: url("/ecosystem/images/market/st.h.png");
}

.symbol-filled {
background-image: url("/ecosystem/images/market/st.o.png");
}

.symbol {
width: 20px;
height: 20px;
}

Readonly Problem

There's something wrong with my readonly rating. I have 5 stars rating with value 5, but rating icon is empty. For rating below 5, it works fine.

Stars hover option

Hello @dreyescat ,

I am trying to show a tooltip (bootstrap) on hover but I can't do that. Have you any solution please?

Regards.

Not working on Ruby on Rails project.

Hey there!

First of all, thank you for making this. Of all the plugins I could find, this one seems the most useful for my purposes.

I'm having a little trouble running this RoR.

I've imported four files into my project. "bootstrap-ratings" ,"bootstrap-ratings.min" and "Gruntfile" javascripts in my application.js file, and "bootstrap-rating.css into mi application.scss file.

application.js
//= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . //= require bootstrap-sprockets //= require bootstrap.min //= require bootstrap-rating //= require bootstrap-rating.min

aplication.scss
@import "bootstrap"; @import "bootstrap.min"; @import "bootstrap-rating";
When I use in my view, it looks fine, but if I try to use $('input').rating(2);for example (setting the rating to default to 2) in my reviews.coffee file ('Reviews' is the controller I'm using in this project) I get the following error.

Uncaught TypeError: $(...).rating is not a function

Also, if I try to attach an event, like in the example:

$('input').on('change', function () {
  alert('Rating: ' + $(this).val());
});

I'm getting SyntaxError: [stdin]:5:25: reserved word "function"

What am I doing wrong? Any help is greatly appreciated.

onchange is triggered twice

This is triggered twice, because already exists in plugin

$('input').on('change', function () {
alert('Rating: ' + $(this).val());
});

CSS classes very generic

The classes in your CSS are rather generic. I'm going to have to do some LESS "namespace trickery" to make sure they don't clash with any of the other classes in our rather large and complex site.

valid html

Hi
Thank you for an awesome, and very simple rating plugin!
I tried validate my html after adding your plugin, but this setting:

is not valid html. input with type "hidden" does not have a readonly property.

Issue with multiple ratings on iOS devices

On any iOS device, I have a problem with multiple ratings. For example I can choose 3 stars for the first rating. When I try to select 4 stars in the next row, it modifies somehow randomly the rating from the previous row! After investigating a bit, it seems the rating value is not updated everytime wrt to the number of stars displayed, especially when the touch is at the border of the rate symbols...
The plugin works perfectly on Android and desktop.

Problem with multiple ratings under iOS7

On my iPhone 4 I have a problem with multiple ratings. For example I can choose 3 stars for the first rating. When I try to select 4 stars in the next row, the selection from the first row is lost!?

Any Suggestions?

Value not receiving angular variables sometimes

<input type="hidden" class="rating" data-fractions="10" id="ho_rating" value='{{rating}}' data-readonly data-filled="fa fa-star fa-2x" data-empty="fa fa-star-o fa-2x" />

the above code not showing stars.

$('input.rating').rating(); initializes the ratingstars twice

When explicitly calling $('input.rating').rating(); the bootstrap-rating is initialized twice.

Is this a desired behavior? A workaround is setting a different class.
If this is planned I would propose adding this to the doku.

Another solution would be adding a param:
e.g. $.fn.rating.defaults.autoInit = false;

Cheers bizarrochris

Size of Stars

How can we change the size of the glyph icons, I've can't figure out how to make them larger ...

about setting initial value by jQuery

Hi, I tried to set the initial value by jQuery, but I find that the initial value can not be shown unless the mouse flies over it. I also tried to fire the hover event on the rating input, but it doesn't work either...

`````` html```

javascript
$("#evalscore").val(res.evalInfo.score)

Readonly rating with a fractional value

Hi,

very nice plugin. Thanks for sharing.

in the demo under Readonly rating with a fractional value, the value is 2.5 which should fill 2.5 stars but it only fills 2.

Is it possible to show 2.5 stars filled?

Thank you.

Programatically set the value

Hello!

Is it at all possible to set the value of a bootstrap-rating displayer programatically?
I noticed another issue posted about it but it was subsequently closed without any information on a solution.
Regards

Include Font Awesome icons

Hello @dreyescat ,

I have a new suggestion. Could you add font awesome icons pack? The implementation is very similar to Bootstrap's icons.

With this new feature your plugin could be more awesome :P.

Thank you :).

Singular Filled Icon

Would it be possible to make the selected rating be the only filled icon?

Something along this line:

ratings-example

Tool tip not showing

I am trying to integrate it in my site, plugin is working fine but tooltip is not showing. Can u please help?

Load JavaScript file using jQuery.getScript()

I just tried to load the .JS file using jQuery.getScript() :

$.getScript("templates/js/bootstrap-rating.min.js", function() {
    $('input.rating').rating({
        filled: 'fa fa-star',
        filledSelected: 'fa fa-star',
        empty: 'fa fa-star-o'
    });
});

I found that customized rating symbols not override defaults, while work just fine when it was first included in HTML file!. Any help?

Cannot display 10 stars, shows all empty

Using either:

input type="hidden" class="rating" data-start="0" data-stop="10" readonly="readonly" value="10"
Or even:
input type="hidden" class="rating" data-start="1" data-stop="10" readonly="readonly" value="10"

Displays empty stars.. No option for full rating.

Also, setting data-fractions="2" doesn't display value="9.5" properly.

I'm talking about setting manual values only.

Create an NPM Package

Hi,

It sould be interesting to create an NPM package. You already have a package.json on your project so it could be interesting to publish it on NPM

Thx

How to unselect the selected first star

Hi
I have implemented your plugin in my app. However how do you unselect the first star after it has been selected

You can unselect the other starts by clicking on the previous star but how do you unselect the first star after it has been selected.

Many thanks in advance

Data fraction go wrong for RTL wrappers

Hello,
I just noticed while implementing the code that data fraction is some how reversed direction on.Hover:

<input type="hidden" class="rating" data-fractions="2" value="4.5"/>

I get to fix the value="4.5", since the half star visible on page load was also reversed by changing this snippet .js (left:0 => right:0):

overflow:"hidden",right:0,width:0

However, didn`t get to fix the half star hover issue.

Half Ratings with Customized Tooltips

First of all, excellent plugin. Congratulations!

I do have one question/suggestion: is it possible to display half ratings in tooltips?
When I enabled "half ratings", I only see integer numbers in the tooltips (example: "Rate 4") even though the half stars are being correctly displayed. Am I missing something?

Thanks in advance for any help.

How to make it work in loop?

Hi, I have a loop $.each , which shows dynamically 6 grades with star rating for each. I tried to inject .rating() to the loop, but no success. How makes .rating() work and show stars for every grade input field in the loop? Thank you.

For example:
$i = 0;
$.each(response, function (key, value) {
i++;
$('.input-grade').append(getHtml(i,
value.grading_criteria_id,
value.grading_criteria.name,
value.grading_criteria.description,
value.grade
));
$('input.grade-rating-' + i).rating({
filled: 'fa fa-star fa-sm',
filledSelected: 'fa fa-star fa-sm',
empty: 'fa fa-star-o fa-sm'
});
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.