jQuery Raty – A Star Rating Plugin

jQuery Raty is a plugin that generates a customizable star rating. (Demo)

Required files:

+ jquery.raty.min.js
+ star-on.png
+ star-off.png

Default configuration:
$('#star').raty();
<div id="star"></div>
Demo:

http://wbotelhos.com/raty

Please:

- Format your code before paste it here, I will probably have to read it;
- Use code formatter to write it:

[source language="javascript"]your_code_here[/source]
Share
  • sakhshi sharma

    janeiro 14th, 2012

    Responder

    hello how to use a hidden field in the plugin and pass its value to ajax ?

    [/source]

  • Miles

    janeiro 10th, 2012

    Responder

    Is there a way to use star ratings hosted on a different domain than the site (eg, a CDN). For instance, if my site is example.com, and my cdn provider’s domain is example.org, I’d like to have star-on and star-off on example.org. I’ve tried setting path to ” (but that just adds a “/” to the beginning of the url) and setting it to null/undefined (which prevents the page from loading).
    Thanks!

  • Miles

    janeiro 10th, 2012

    Responder

    Is there a way to host the star images on a CDN, or different domain? That is, website domain = example.com, but the images live on example.org. Setting $.fn.raty.defaults.path to ” puts a forward slash in front of the img src (eg /http://example.org/blah. Setting it to null (or undefined) prevents the page from loading.
    Thanks!
    miles

  • Kelvin

    dezembro 30th, 2011

    Responder

    Hi,

    I have a small problem with my code. First of all Raty works fine! I really like it, until you add some effect to the div that Raty is currently in than all the stars just disappear. I tried to use the built-in function of jQuery “Live” it works.. but I don’t know how to apply it to the Raty function within an ‘each’ method without getting into a loop where you have multiple set of stars per thumbnail. Maybe you guys can help me out?

    P.S.: These are all thumbnails, which each of them have their own one set of stars (* * * * *).

    Here is the code:

    
    		$('[class^=stores_starRated]').each(function()
    		{
    			var starRated	=	$(this).attr("id").replace("-", ".");
    			starRated		=	(parseFloat(starRated)) > 0 ? parseFloat(starRated)	:	0;		
    
    			$(this).raty
    				({
    					start: starRated,
    					half:  true,
    					space: true,
    					targetKeep: true,
    					path:   	'public/images/default/icons/',
    					hintList:	['bad', 'poor', 'regular', 'good', 'gorgeous'],
    					number:		5,
    					click: function(score, evt)
    					{
    						var store_id	=	$.trim($(this).attr('class'));
    						var score		=	$.trim(score);
    
    						if(store_id != '' && score != '')
    						{
    							//do something here//
    						}
    					}
    				});
    		});
    
    • wbotelhos

      dezembro 30th, 2011

      Responder

      Hi Kelvin,

      You can use the callback on start option directly:

      $('[class^=stores_starRated]').raty({
          start: function() {
              var starRated = $(this).attr("id").replace("-", ".");
              return (parseFloat(starRated)) > 0 ? parseFloat(starRated) : 0;
          }
      })
      
  • Brian

    dezembro 29th, 2011

    Responder

    I have run into one problem, I’m building a jquery mobile site and your big star rating is perfect in appearance and size but when its placed inside a div with the rating disappears. If I remove the data-role=”page” the stars appear. Now I have to have the page role, and I’m lost at how jquery really works. I’ve tried adding your plugin before the mobile scripts, after, on the page after the star dive and before.

    • wbotelhos

      fevereiro 5th, 2012

      Responder

      Hi Brian,

      Raty has no problem with data-role="page". Just make sure not to declare this property on the same page more than once. For the rest should be some silly little mistake.

  • renars

    dezembro 22nd, 2011

    Responder

    Hi!

    I have following problem. alert gives me correct value, but it is not taken as start

        $('.rating').raty({
            click: function(){
                alert('test rating. val = ' + $(this).attr('value') );
            },
            start: $(this).attr('value')
        });
    

    ‘ssil’ user wrote about some jQuery conflicts. is this the one? how could I solve this issue?

    • wbotelhos

      dezembro 22nd, 2011

      Responder

      Hi renars,

      The $(this) will only be the Raty container if it is within the callback.
      Use this:

      start: function() {
          return $('this').attr('value');
      }
      

      I never had conflict problems with Raty in any project.

      • renars

        dezembro 22nd, 2011

        Responder

        Yes, ‘return’ makes difference. thanks! :)

      • renars

        dezembro 23rd, 2011

        Responder

        Should following statement work aswell if ‘testattr’ is my attribute which value is set to ‘true’ or ‘false’?

        readOnly: function() { return $(this).attr(‘testattr’) }

        • wbotelhos

          dezembro 23rd, 2011

          Responder

          Hi renars,

          Callback works just for start option.
          If you want set it to read-only, use the function readOnly(true).

  • Robin Henriksson

    dezembro 20th, 2011

    Responder

    Hello!

    Very Nice Plugin, thank you very much for this!

    But one question:

    I use raty with a half value, and when i have rated one div, and for example hit 4.5, the hintList get the value of Number 4 (good) instead of number 5 (gorgeous), Why?
    if it is 4.5, it should get it from number 5, am i wrong?

    how can i change this?

    thank you in advance

    Regards
    Robin

    • wbotelhos

      dezembro 22nd, 2011

      Responder

      Hi Robin,

      The hintList do not show half values, just the integer values.
      You can adjust the round option, but the hintList still will present just integer values, because we don’t have hintList position to set each decimal value.
      Anyway, to solve that an option like hintPopUp: true will be created to display the exact value on mouseover.

  • Guillermo

    dezembro 12th, 2011

    Responder

    Is there a way to clear raty plugin from the targets? I need to do this to avoid re-attaching the plugin, but also to free some memory in an ajax based web. So, a way to detect if raty is already attached would be good, and a way to unbind the plugin would be better for me. I’m trying this and can’t get it to work:

    $(".slide li .rating img").unbind("click").unbind("mouseenter").unbind("mouseleave"); 

    Thanks in advance.

    • wbotelhos

      dezembro 18th, 2011

      Responder

      Hi Guillermo

      - I did not understand “clear raty from the targets”;
      - If the container has elements inside is because it is binded (quick solution);
      - Unbind what? With you want unbid the click, mouseover and so one, just turn it readOnly.

      • Guillermo

        dezembro 19th, 2011

        Responder

        Thanks for your reply. Yes, right now i’m using something like this to check if element has raty enabled:
        $(“li .rating”).first().find(“img”).length == 0)

        - By “clear raty” i mean leave the “targets” in there original state. By target i mean the element receiving the plugin modification. Ex: $(“span.raty”).raty() // the span is the target

        - By unbinding i mean unbind the events of the elements. See, if i delete the html but then i regenerate it using ajax searchs, then the events attachs twice.

        Well, it’s hard to explain. Anyway thanks. I’ll find a way using conditional.

  • ssil

    dezembro 11th, 2011

    Responder

    I use the raty plugin in one of my pages. But I am not able to retrieve the score. Below is a simple code where I try to alert the value of ‘score’ (eg from site). But I do not get the alert message after I click on the stars. I am sure I am missing something. Can you please help me here:

        <head>
            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <script type="text/javascript" src="JavaScript/jquery.js"></script>
            <script type="text/javascript" src="JavaScript/jquery.raty.min.js"></script>
    
        </head>
        <body>
            <div id="click"></div>
        <script type="text/javascript">
            $(function() {
                $('#click').raty({
                    click: function(score, evt) {
                        alert('ID: ' + $(this).attr('id') + '\nscore: ' + score + '\nevent: ' + evt);
                    }
                });
            });
        </script>
     </body>
    
    • wbotelhos

      dezembro 11th, 2011

      Responder

      Hi ssil,

      Here it worked fine.
      Maybe your import is wrong.

      • ssil

        dezembro 12th, 2011

        Responder

        Yes. I think there were jquery conflicts which caused the issue. I have now resolved it.

        Thanks for the help.
        And Thanks for the simple, nice and neat plugin.

  • zy8008

    novembro 30th, 2011

    Responder

    I’m Sorry my english is not good !
    please look my code:

    $('#TravelPoint').raty({
        'target': '#hTravelTarget',
        'click': function(score, evt) {
            $("#hdTravelPoint").val(score);
    	    SumTotal();
    	}
        });
    
    $('#GuidPoint').raty({
        'target': '#GuidTarget',
        'click': function(score, evt) {
            $("#hdGuidPoint").val(score);
            SumTotal();
        }
    });
    
    $('#HotelPoint').raty({
        'target': '#HotelTarget',
        'click': function(score, evt) {
            $("#hdHotelPoint").val(score);
    	SumTotal();
        }
    });
    
    function SumTotal() {
        var p1 = parseFloat($("#hdTravelPoint").val());
        var p2 = parseFloat($("#hdGuidPoint").val());
        var p3 = parseFloat($("#hdGuidPoint").val());
        var sum = parseFloat((p1 + p2 + p3 ) / 3);
    
        $("#hdTotalPoint").val(sum);
        $('#TotalPoint').raty('start', sum);
    }
    

    when click the raty . i will save this value to a hidden control, when i sum this point , i must load this value for hidden control. do you Have the direct read value method.

    e.g:

    var p1 = parseFloat($('#HotelPoint').raty().value());
    

    thank you very much!

    • wbotelhos

      novembro 30th, 2011

      Responder

      Hi zy8008,

      No it does not exist, but is a good idea.
      Could you open a issue for it here [1], please?

      For now, you can get the value using jQuery with function:

      var p1 = parseFloat($('#HotelPoint').find('input').val());
      

      You have some typos. The targets missing the “hd” on begin. And you don’t need to put the option click inside quotes.

      And more, the right thing to do is keep this values on database then, you will get the average through an ajax query. It’s never good to do business logic in a view.

      [1] http://github.com/wbotelhos/raty/issues

  • zy8008

    novembro 28th, 2011

    Responder

    Hi, at first i loving the plugin,but i have a question,how i can get another raty value

    • wbotelhos

      novembro 28th, 2011

      Responder

      Hi zy8008,

      I did not understand your question.
      We have just one value for each Raty.

  • Mark

    novembro 24th, 2011

    Responder

    Hi, loving the plugin, but getting the following error when trying to set the score after the ajax post:

    Object doesn’t support property or method ‘start’

    Code is as follows:

    $(document).ready(function(){
    	var pathname = window.location.pathname;
        $('#rateplugin').raty({path:'/img/', half:true,
           click: function(score){
           var dataString = 'pathname='+pathname+'&amp;score='+score;
            $.ajax({
            type: "post",
            url: "/services/ajax-rating.asp",
            dataType: "text",
            data: dataString,
            success: function(data){
            	$.fn.raty.start(data, '#rateplugin');
     		$.fn.raty.readOnly(true, '#rateplugin');
                 }
             });
          }
        });
    });
    

    I’m using version 2.0.0. I’m sure its something simple, just can’t figure it out. Thanks!

    • wbotelhos

      novembro 24th, 2011

      Responder

      Hi Mark,

      The public functions changes on version 2.x, then use:

      $('#rateplugin').raty('start', data);
      $('#rateplugin').raty('readOnly', true);
      

      You can to use chain if you want.

      • Mark

        novembro 24th, 2011

        Responder

        Thanks Washington,

        You’re a legend! ;-)

  • André Steinn

    novembro 18th, 2011

    Responder

    Well, I know how to write/read the avg in database…
    But, I would like to show to the user two things:

    His vote
    The average rate (with all votes).

    So, the stars could show the average and some title=”", the user vote…

  • Evgeniy

    novembro 18th, 2011

    Responder

    How can I write rating into a database and retrive rating from dababase?

    • wbotelhos

      novembro 18th, 2011

      Responder

      Hi Evgeniv,

      This depends on the programming language you are using.
      There is no something trivial or a cookbook, it’s best you know a programming language and implement it. And that is outside the scope of Raty or any other plugin.

  • Márcio

    novembro 17th, 2011

    Responder

    Parabéns pelo plugin, o melhor que encontrei! Simples e funcional!

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Márcio,

      Thank you!
      The version 2.0.0 will bring a bunch of new features and fix.
      Maybe it’ll be released on next week.

  • André Steinn

    novembro 16th, 2011

    Responder

    Another thing…
    If the user already voted (I saved in database),
    I could show him the average rate (from all other users), and when he passes the mouse over the ratings I show: “You already voted in this item, your vote: 8.5″.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi André,

      Average is a job for your application.
      Raty just capture and show the value you want, but who calculates it is you.

  • André Steinn

    novembro 16th, 2011

    Responder

    Well, I have a suggestion.
    If I have more than one rating element in one single page, I need call raty() for each element… I think the plugin could call all elements if I use some attribute like data-rating.
    For example:

    Call the plugin once would better:
    $(“.raty”).raty();

    another thing, I could define the options before call the plugin…
    $.raty.options = {
    readOnly:true,
    noRatedMsg: ‘Essa legenda não foi classificada ainda!’,
    hintList:['Horrível', 'Ruim', 'Mais ou menos', 'boa', 'Ótima!']
    }

    When I run the script, It could use this options…

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi André,

      If you want bind a couple of raty, just use class bind:
      $('.star').raty();

      To override globally, just override the defaults configurations, like start with 1 instead of 0:
      $.fn.raty.defaults.start = 1

  • André Steinn

    novembro 12th, 2011

    Responder

    Curti pra caralho o plugin, procurava algo pra rápida implementação no sistema e ainda algo personalizável, bonito e funcional.
    Ótimo trabalho, feito por um brasileiro ainda (Y)

  • Mike

    novembro 8th, 2011

    Responder

    Fixed the issue. See that you don’t use opt.halfShow in your code but it’s documented here:

    http://www.wbotelhos.com/raty/#fixed-demo

    • wbotelhos

      novembro 8th, 2011

      Responder

      Hi Mike,

      Try to use the script from repository code.
      It was my mistake, because the new version will be released yet.

  • Mike

    novembro 8th, 2011

    Responder

    Hi. I downloaded latest version “version 1.4.3″ and I think I found a bug.

    I want to display half stars, but only let the user to select full starts. I am using this settings.

    half: false, halfShow: true, start: 3.5

    But it will not let me show half stars (3.5) and DONT let the user select 1/2 stars.

    I will look into your JS file now, perhaps I can fix it.

    Regards
    Mike

    • wbotelhos

      novembro 8th, 2011

      Responder

      Hi Mike,

      If you want select half star then change half option to true.

  • unnamed

    outubro 19th, 2011

    Responder

    Hi,
    I checked out a lot rating plugins. This seems good. There is a pretty simple image change option.
    Quickly question: Why there is no support for input type fields ? input names, values ??
    The first plugin is at “http://www.fyneworks.com/jquery/star-rating/” .
    Check it out the link, there is an option for radio buttons and values. For example, the user can post the input values to the server. Do you think to add this option ? Regards.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi unnamed,

      Raty don’t use input because it is create automatically.
      What you want to say with input names and values?

      I know this plugins and I created Raty because that and other does not meet my needs. Raty has a hidden field that support the value (score). You don’t need five or more fields to keep just one value.

  • Udit

    setembro 9th, 2011

    Responder

    I’m having trouble getting Raty to work from inside a modal popup (Using jqueryui Dialog). The readonly bit works fine but any user interaction doesnt work. Any ideas?

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Udit,

      I should work inside a modal.
      If readOnly is enable, then the interaction (mouseover) will does not work anyway.

  • Oudin

    setembro 6th, 2011

    Responder

    Is there a way to allow somebody to vote/rate an item only once.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Oudin,

      You can set the raty as readOnly using public funcion after the click.

  • VLRao

    agosto 30th, 2011

    Responder

    i applied raty for the items in a loop by calling this function dynamically

    applyStatusRaty_ForGoal(status_col, row_index);
    

    This is the function definition:

    function applyStatusRaty_ForGoal(currentElemet, row_index_col) {
        ratyJquery("#" + currentElemet).raty({
            number: 5,
            hintList:  ['1', '2', '3', '4', '5'],
            scoreName: 'status',
            path: Drupal.settings.themePath,
            starOff: 'status_default.gif',
            starOn:'status_star.gif',
            start: 0,
            target: null,
            targetKeep: false,
            targetType: 'hint',
            onClick: function(score, event) {
                var currentGoalID = $("#" + row_index_col).val();
                var params = "goal_user_id=" + currentGoalID + '&amp;status=' + score;
    
                $.ajax({
                    type: "POST",
                    url: Drupal.settings.baseUrl + '/update_goal_status',
                    data: params,
                    success: function(result) {
                        manipulateUserGoals(result);
                    }
                });
            }
        });
    }
    

    Its working fine. But when my click event firing morethan one time. So how can i remove that event for the items. while page content modified by ajax call back request.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi VLRao,

      The callback will fire more than once just if you click more than once.

      You can block the raty while ajax request with read only and on complete you take off the read only.

  • rory

    agosto 29th, 2011

    Responder

    I was wondering if you seen my last question on your raty plugin?

  • Caio Marques

    agosto 26th, 2011

    Responder

    Hi,

    First time using this very good plug-in!
    =]

    I’m using this rating plug-in for a survey, and I populated a page with a set of ratings with diferents IDs and I have configured each one to fill the rating score to a specific hidden field. When i’m reading this values I’m getting they whith a comma in the end.
    If someone rates 5, for example, I will read this: “5,”
    Ratings not filled I read a single comma, like this:”,”

    What I’m doing Wrog?
    I’m using the 1.4.3 version.

    Please, see the code below:

    $(‘#rating_’XXX).raty({
        size: 24,
        starOff: ‘star-off-big.png’,
        starOn: ‘star-on-big.png’,
        scoreName: 'score_XXX',
        target: ‘#hint_XXX’
    });
    
    • Caio Marques

      agosto 29th, 2011

      Responder

      I found what is causing my problem.

      For each rating I’m using a asp.net hidden field to store the score value. This field is necessary for me because I need to read the stored values at server side. (in my page I have a lot of ratings, about 15… a need to read each one and save the data using asp.net controls).

      Because of it, the property ‘scoreName’ of raty, is set dynamicaly at the same time my asp.net hidden field is created (store property is setted to the same id of hiddend field created).

      The problem is: raty creates the hidden field and asp.net (me) create the hidden field too! Because they have the same name, the post concatenates the values (separated by commas) of this diferent fields because they have the same name.

      There is some way to stop raty creating the hidden field? I just want to tell the raty the field name wich its need to store the value. There is some way to do this?

      • wbotelhos

        novembro 17th, 2011

        Responder

        Hi Caio,

        Raty always set the score into the hidden field inside the Raty. You can make a function on your click callback that get the score and set it into other field to.

        The name you can change anyway.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Caio,

      Your score is coming with comma or you want put a comma after your score?

  • Sandhya

    agosto 25th, 2011

    Responder

    Hi,

    Great plugin.

    One query: I want to enable the cancel button only when user selects score > 0, other wise cancel button should be disabled.

    Thanks.

    • wbotelhos

      agosto 30th, 2011

      Responder

      Hi Sandhya,

      You can enable and disable it inside the click callback.

      • Sandhya

        agosto 30th, 2011

        Responder

        Hi,

        Thanks for the reply.
        But I am unable to integrate the code in click event. Can you please post the sample for it?

        Thanks.

        • wbotelhos

          setembro 9th, 2011

          Responder

          Hi Sandhya,

          Do the following steps:

          - Enable it on Raty first cancel: true;
          - Disable it when your page loads inside the ready function $(function() { // here }).
          - On click check the score and hide or disable the click on cancel or cancel container:

          $('#raty').raty({
              click: function(score) {
                  if (score > 0) {
                      // enable
                  } else {
                      // disable
              }
          });
          
  • Wang

    agosto 25th, 2011

    Responder

    I’m having this bug. This is my code:
    html:
    2
    4

    $('div[name="rating"]').each(function() {
        var rating = parseInt($(this).html());
    
        $(this).html('');
        $(this).raty({ readOnly: true, start: rating });
    });
    

    The rating stars were shown but it always show 4 stars for both DIV although I’m sure that start value is right (I alerted the raty options to make sure it’s right).

    Please help me solve this problem. Thanks.

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Wang,

      It should work, but using version 2.x is possible to use start option like callback, and inside it you can get any attribute you want, like:

      start: function() { $('this').attr('some-attr') }

      Its easier.

  • Rory

    agosto 22nd, 2011

    Responder

    Sorry one last question.

    Is there a way to make it so that each one of the off images (staroff) are different in same way iconRange can make them different?

  • Rory

    agosto 22nd, 2011

    Responder

    I have tried doing it this way but it does not seem to work.

    $('#no').raty({
        iconRange: [['face-c.png', 1]],
        starOff: 'face-off.png',
        hintList: ['I never met this person.'],
        target: '#meetHint',
        size: 35,
        number: 1,
        click: function(score) {
            $.fn.raty.cancel('.yes');
        }
    });
    
    $('#yes').raty({
        iconRange: [['face-e.png', 1]],
        starOff: 'face-off.png',
        hintList: ['I have met this person.'],
        target: '#meetHint',
        size: 35,
        number: 1,
        click: function(score) {
            $.fn.raty.cancel('.no');
        }
    });
    
    • wbotelhos

      agosto 22nd, 2011

      Responder

      Hi Roy,

      You must call by ID [1], not class [2], because your bind was by ID: $('#yes')

      [1] $.fn.raty.cancel('#yes');
      [2] $.fn.raty.cancel('.yes');

  • Rory

    agosto 19th, 2011

    Responder

    I would like to reset the rating one of the lines that has been rated if the other one currently has a rating and vice versa. The two ratings are

    $('#good').raty({
        iconRange: [['face-a.png', 1], ['face-b.png', 2], ['face-c.png', 3], ['face-d.png', 4], ['face-e.png', 5]],
        starOff: 'face-off.png',
        size: 35
    });
    
    $('#bad').raty({
        iconRange: [['face-a.png', 1], ['face-b.png', 2], ['face-c.png', 3], ['face-d.png', 4], ['face-e.png', 5]],
        starOff: 'face-off.png',
        size: 35
    });
    

    Anyone have experence on how to go about this?

  • Jangla

    agosto 19th, 2011

    Responder

    I’m trying to use this on a single element with a class and I get an error on mouseover the stars. Works fine if I use an id.

    Is this a known problem?

  • David

    agosto 17th, 2011

    Responder

    Hi Washington!

    Your plugin seems really handy and simple. I like it a lot!

    However, I seem to be missing something since I’m having some trouble with my images.

    My starOn, starOff custom images are in a separate folder and I’ve specified both the path option and the star filename when initializing Raty.
    However, when I load the page my images are broken. It is not until I hover over Raty that the images show up correctly.

    This is my initialization (I’m using CodeIgnitier):

    $('#attribute_10').raty({
        path: 'img/usr-item/',
        starOn: 'star_on.png',
        starOff: 'star_off.png',
    });
    

    However, this is the code that Raty produces on first load:

    “You code did not appear. Use the tag <pre>”

    As you can see, it ignores the path variable.

    After I hover over the images, the src gets updated and the images show up correctly:

    “You code did not appear. Use the tag <pre>”

    Did I miss a config variable?

    Thanks a lot for your help, cheers !!

    • wbotelhos

      agosto 19th, 2011

      Responder

      Hi David,

      I got no problem here.
      I tested with the same names and paths.

      The results was img/usr-item/star_on.png and img/usr-item/star_off.png.

  • Tina

    agosto 14th, 2011

    Responder

    I have a question about the file js/jquery.min.js..it seems to be conflicting with the needs of some of my other scripts (different version). Any ideas on how to fix that? Right now, if I take that call out everything else works. I’m not sure how to marry them all.

    • wbotelhos

      agosto 19th, 2011

      Responder

      Hi Tina,

      Try to use the version that are not minified and try debug with Firebug or something to try figure out.
      Try to see if you’re not referencing the same ID or class too.
      Just with your words, I have no ideia. =/

  • Cronix

    agosto 11th, 2011

    Responder

    If raty is set to readOnly, custom hintList is ignored (first in array gets used on all stars).

    Also, when set to readOnly, click event is ignored.

    • wbotelhos

      agosto 11th, 2011

      Responder

      Hi Cronix,

      On readOnly the hint of the selected score is used to show.
      And when readOnly is enabled, nothing works, because it must to be read only.

      • Cronix

        agosto 11th, 2011

        Responder

        Thank you for the swift reply :)

        I believe when readOnly is used, it should still apply the correct hint for each star so that people can hover over each one to see what each star represents.

        For click event I just used

        $(selector).raty({
            readOnly: true
        }).click(function(){
            //custom click code
        });
        

        to overcome it. I wanted it to open a tab that had more things to rate and the main raty is just the average.

        • wbotelhos

          agosto 29th, 2011

          Responder

          It worked like you said, but did not please many people just like me. readOnly is to present the chosen value and nothing more.

          The workaround is a good option because the internal behavior cannot break the rules of the readOnly option.

  • krisu

    agosto 9th, 2011

    Responder

    Hello, how can I delete space between stars?

    Is it possible to keep the score both in a select (I need this for MySQL) and in div?

  • Tice

    agosto 3rd, 2011

    Responder

    Hello

    Nice script! But how can I send the score when I use this in a form? I use the plugin 5 times (rate_1, rate_2, …). How can I send each value in a correct way?

    Thanks.

    • wbotelhos

      agosto 11th, 2011

      Responder

      Hi Tice,

      You have a attribute called scoreName to identify you score.
      When you submit your form this score goes together with that identification.

      Your you can send by ajax submit instead a form submit.

  • Asad

    julho 23rd, 2011

    Responder

    hello i am having a strange problem when i use your plugin with the id selector it works fine but when i use class selector then hover effect didnt work on stars

    • wbotelhos

      julho 23rd, 2011

      Responder

      Hi Asad,

      The example on documentation works for you?
      What browser and version do you use?

  • greg

    julho 19th, 2011

    Responder

    Great plugin! I was hoping to be able to use the same plugin and code for a thumbs up/down kind of rating, but unfortunately that doesn’t seem to be possible, due to the fact that we can only use one single image for all “off” icons.

    Trying this, but doesn’t work for the reason mentioned above.

    .raty({
        number: 2,
        hintList:  ['no :(', 'yes!'],
        iconRange: [['thumbs_down.gif',1], ['thumbs_up.gif',2]]
    });
    

    It might add a great deal of flexibility if one was able to do the following:

    .raty({
        options: [
            {on: 'first_on_icon.gif', off: 'first_off_icon.gif', value: 1, hint: 'first rating value'},
            {on: 'second_on_icon.gif', off: 'second_off_icon.gif', value: 2, hint: 'second rating value'}
        ]
    });
    

    WDYT?

    • wbotelhos

      julho 29th, 2011

      Responder

      Hi Greg,

      The thumb rating is a great idea, but it just pays to be developed if exists an option to enable only one star as thumb rating, because enable multiple values ​​to multiple star generates a very high level of complexity that will not do well for the purpose of the plugin.

      One option that on each click the icon, value and hint changes like:

      thumb: [
          { icon: 'thumb-off.gif', value: null, hint: 'No rating yet!' },
          { icon: 'thumb-up.gif', value: 1, hint: 'Like +' },
          { icon: 'thumb-down.gif', value: -1, hint: 'Dislike -' }
      ]
      

      What do you think?

      • greg

        agosto 2nd, 2011

        Responder

        Hi,

        I’m not sure I understand what you mean – would “thumb” be a new option in raty, a new plugin altogether, or … something else entirely ?

        • wbotelhos

          agosto 29th, 2011

          Responder

          I was thinking about to change just one icon on each click to differents icons.

          But what you sad is a kind of iconRange with option for starOff, like:

          iconRange: [['star-1-on.png', 'star-1-off.png', 1], ['star-2-on.png', 'star-2-off.png', 2]
          

          I’ll create some issues.
          Thanks.

  • alex

    julho 18th, 2011

    Responder

    Hello, I tested on IE8,7,6 (through IETester) and it seems there is an error, can you confirm it works in those browsers?

    • wbotelhos

      julho 23rd, 2011

      Responder

      Hi Alex,

      You’re right, there was an error caused by the last updates.
      Please use the last version: https://github.com/wbotelhos/raty/downloads

      Thank you.

      • Alex

        julho 29th, 2011

        Responder

        @wbotelhos

        Thanks, the plugin seems it works fine now but the ‘group’ & ‘directed actions’ examples do not work correctly in IE again. I saw that both use classes instead of IDs, so there might be an issue with using classes as selectors with the plugin.

        • Alex

          julho 29th, 2011

          Responder

          To add to this: Problems only occur in IE6,7 not 8

        • wbotelhos

          novembro 17th, 2011

          Responder

          Hi Alex,

          The public function was fixed some versions ago.

  • Stioune

    julho 16th, 2011

    Responder

    Hi,
    I try to implement raty in a GMap InfoWindow (as marcela I think) but it doesn’t appear.

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                map: map,
                title: locations[i][0]
            });
    
        markers.push(marker);
    
        google.maps.event.addListener(marker, &#039;click&#039;, (function(marker, i) {
            return function() {
                contentString = '&#039;' + locations[i][0] + '  &raquo;&nbsp;Set as my local track | Set as a favorite track';
    
                infowindow.setContent(contentString);
                infowindow.open(map, marker);
            }
        })(marker, i));
    

    How can I add my raty in my contentString ?

    Thanks for your help

    • wbotelhos

      julho 16th, 2011

      Responder

      Hi Stioune,

      I don’t know how to use Maker, but I think you put the Raty code inside the callback.

  • Dev

    julho 8th, 2011

    Responder

    How can I increase the spacing between the stars?

    • wbotelhos

      julho 14th, 2011

      Responder

      Hi Dev,

      Using JS:

      $('#rating').children().css('margin-right', '10px');
      

      Using CSS:

      div#rating img { margin-right: 10px }
      
  • Bbob

    julho 8th, 2011

    Responder

    Hi

    Can anyone help me….the star images are not displaying when I use this

    • wbotelhos

      julho 14th, 2011

      Responder

      Hi Bbob,

      Your code did not appear, you must put it between the following tags:

      [source language="javascript"] .... [/source]

  • James Minter

    junho 14th, 2011

    Responder

    I know for a wiz like you this will sound really elemental, but I’m not really good with Jquery.. but, does your ratings accumulate. Like when one person votes and another person votes will these votes add up and then the third person who sees it will see the 2 previous votes?

    • wbotelhos

      junho 23rd, 2011

      Responder

      Hi James,

      You can display any value on Raty, but it should be calculate based on your database values.
      In each vote, you must persiste the rating, then every time an user goes do a rating, you can display the values accumulated.
      You can’t accumulate the values on client side, because the browser don’t keep the data between the user, you should persiste it.

      That explains your doubt? I not sure if I understood.

  • Fruiko

    junho 14th, 2011

    Responder

    Hi,
    I try cancel voting, when is same star clicked.

    I try something like this:

    click: function(score, evt) {
      if ($('input#ratyblock-score').val()==score){
        $.fn.raty.cancel('#ratyblock');
       } else {
         $.fn.raty.start(score, '#ratyblock');
       }
    }
    

    But isn’t work becase function initialize remove atribute value before I can use it.

    Some idea how fix it?

    • wbotelhos

      junho 23rd, 2011

      Responder

      Hi Fruiko,

      You can’t, because the function is click, not beforeClick. The click callback is called after the click, because the click invoke this callback. You can keep the last value in another hidden field, then you can compare it with the score on the callback. Then just keep that hidden value updated in every click.

      But it can be a new feature, like beforeClick and afterClick maybe.
      Can you open a issue here please?: https://github.com/wbotelhos/raty/issues

      Thanks.

  • John

    abril 30th, 2011

    Responder

    Hi wbotelhos,

    Thank you for your response!

    My code is good working. Problem here is: “How to disable the star then click on it”.

    I think using this function
    $.fn.raty.readOnly(true, '.raty');

    But it not working. Or i put it at a wrong place?

  • John

    abril 30th, 2011

    Responder

    Hi Wbotelhos,

    I have this code
    _____________________________

    $(document).ready(function(){
                $('#default').raty({
                    click: function(score, evt) {
                        $("#loading").css("display","block");
                        $.ajax({
                            url:"HandlerAjax.ashx?d=" + score,
                            success:function(result){
                                $("#").html(result);
                                $.fn.raty.readOnly(true, '.raty');
                            }
                        });
                        $("#loading").css("display","none");
                    },
                    scoreName: 'entity.score',
                    number: 10
                });
            });
    

    ____________________________

    I want to disable star rating when i click on the star to rating. How can i do? Help me, please,
    Thanks and regards!

    • wbotelhos

      abril 30th, 2011

      Responder

      Hi John,

      I think you forgot the ID here: $("#").html(result);

      To disable the stars on click use the public function in the callback like you did.
      Probably your problem is your ajax request, then the public function readOnly is not performed.

      Do the test using readOnly in the click callback that will see it working.

  • Gabs

    abril 28th, 2011

    Responder

    Mando bem ;)

  • Pan W

    abril 27th, 2011

    Responder

    Thanks for the reply. Could you provide me with some suggestions. I have two sets of star rating: (1) user rating and (2) average rating. After a user submits their rate I am trying to also have the new average reflect. Based on how you designed Raty would what I described be possible?

    In Raty click option, I have tried to run a $.post() to retrieve the new average after the user submits and set the new average value to the Raty start option, but that does not seem to work. The code would be as follows:

    $('#userRaty').raty(half:true, click: function(score, evt){
        //do $.post to submit to update user rating for item
       $.post('getAvg.php', {params}, function(avgRating){
            $('#avgRating').raty(start: avgRating);
       })
    });
    

    Sorry about putting code in here. Please let me your suggestions. Thanks.

    • wbotelhos

      abril 27th, 2011

      Responder

      Hi Pan,

      You are on the right way. You should do the persistence of the vote and then take the average.
      In the success callback calculate the average and return it.

      click:	 function(score, evt) {
          $.ajax({
              type: 'GET',
              url: '/vote',
              success: function (average) {
                  $.fn.raty.start(average, '#average');
              }
          });
      }
      

      Here’s an example I made: http://www.moviecollection.com.br/filme/3

      And do not forget the “{}” between the brackets:

      $('#raty').( {} );
      
  • Pan W

    abril 23rd, 2011

    Responder

    What I mentioned was an error on my part. However the image folder path is not correct. I fixed it by creating an identical img folder in a level above my the Raty plugin folder. Is there a cleaner way to fix this?

    • wbotelhos

      abril 23rd, 2011

      Responder

      Hi Pan W,

      You can use the atribute path to set you owner path.

  • Pan W

    abril 23rd, 2011

    Responder

    I am using Raty version 1.3.2.
    When I do this: $(“.someClass”).raty();
    and hoover over or click on the stars it affects all containers with the same class name. Please let me know how I could resolve this.

  • nick

    abril 20th, 2011

    Responder

    Awesome plugin but would be cool to splt parameter ‘half’ to ‘show_half’ and ‘vote_half’.
    Also add mousemove and mouseleave methods not only click.

    I also found a bug, i think. If u set iconRange icons and start value. Then mouse enter and mouse leave the start value will be with iconRange icons and not staron.

  • Dan

    abril 3rd, 2011

    Responder

    It’s not called more than once for the same element. Each element it is called on has a different ID and is within a different parent element.

    The application is a mobile dining application and users can rate a given restaurant or meal. When the user clicks on a meal, it displays the details and rating for that meal. When clicking an additional meal, it of course AJAXes in a similar screen with different IDs. But this is where raty duplicates the row of stars.

    I’ve tried the above code with a specific ID as the selector:

    $('#rating' + id).raty({...});
    

    But that didn’t help either.

    But you are right in that I call the bind code several times (each time a new “screen” is AJAX’d in).

    • wbotelhos

      abril 3rd, 2011

      Responder

      Hi Dan,

      It happens only if the .raty() apply more than one time like this:

      <div class="rating"></div>
      
      $('.rating').raty();
      

      Clicked and added more one raty container…:

      <div class="rating"></div>
      <div class="rating"></div> <!-- the new one -->
      
      $('.rating').raty(); // Applies the new one, but the older one too, duplicating it.
      

      Can you post your code on jsbin.com rawer as possible to me help you in a better way?

      • Dan

        abril 4th, 2011

        Responder

        I figured it out. I was actually calling the bind multiple times. I didn’t realize it because of some nuances with jQuery Mobile.

        Thank you so much for your help. I appreciate it.

        Raty is a slick plugin. Does everything I need simply and efficiently.

  • Dan

    abril 3rd, 2011

    Responder

    I’m trying to integrate Raty into a web based mobile app using jQuery Mobile. It uses ajax to pull in new pages that have raty enabled divs.

    So I have an event for when a new page is created, it looks for the “rating” class and initiates raty for it. The problem is that it is starting to duplicate the stars. Each time I load a new page that has an additional raty on it, it displays another row of stars.

    Is there something I can do to fix this or is it just not possible with Raty?

    • wbotelhos

      abril 3rd, 2011

      Responder

      Hi Dan,

      The Raty you be duplicated just with you call the .raty() more than one time in the same page without refresh it.

      If you want to load one extra div to become a Raty element without refresh the page, you must apply the raty just in this element in the same function that created the div like:

      $(<div class="raty"/>).appendTo('#wrapper').raty();
      
      • Dan

        abril 3rd, 2011

        Responder

        I’m not sure I understand. What is #wrapper? Is that the div that I loaded through ajax?

        Here’s my markup:

        And my code:

        $('.rating').raty({
            half: true,
            start: $('#rating-' + id).attr('data-rating'),
            hintList: ['bad', 'poor', 'regular', 'good', 'awesome'],
            path: '/img/raty/',
            click: function (score, evt) {
                var item = $(this).attr('data-id');
                var type = $(this).attr('data-type');
                $.ajax('/index/rating', {
                    data: {id: item, type: type, rating: score},
                    type: 'POST'
                });
            }
        });
        
        • wbotelhos

          abril 3rd, 2011

          Responder

          Hi Dan,

          It was just a example of a div to keep the rating.

          How many times do you call this bind code?: $('.rating').raty({ ... });
          The problem occurs after the click function?
          How do you are including the new raty?
          Do you refresh the page to rebind the raty or do that without refresh?

          Make sure you are not calling the raty more than one time for the same elements.

  • Reda

    março 30th, 2011

    Responder

    sorry, some of my texts haven’t been taken:

    Hi,
    I tried to use $.fn.raty.start(2, ‘#star’); as you mentioned but didn’t work!
    i used it that way:

    $.fn.raty.start(2, ‘#star’); just before the

    isn’t it possible to make it easier by putting the value inside de div:

    ??

    Thank you so much

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Reda,

      You can set the option start to do that.
      The new version 2.0.0 will support callback on option start, then will be possible do like this for example:

      start: function() { $('this').attr('some-attr') }

      Next week it will be released.

  • moshe

    março 12th, 2011

    Responder

    Thanks!

    yes, i have –

    and re the start number – sorry, i really do have it, but it didnt paste through (it’s a dynamic variable from ASP)

  • moshe

    março 11th, 2011

    Responder

    hey there

    thanks for this amazing plugin – just what i wanted!

    i am running into the following error:
    Error: console is not defined
    Source File: xxxx/includes/jquery.raty-1.3.2/js/jquery.raty.js
    Line: 201

    and this is my code:

    $('#rating').raty({
        start:     ,
        number:     5,
        cancel: true,
        half:  true
    });
    

    any idea what the issue could be?
    Thanks!

    • wbotelhos

      março 11th, 2011

      Responder

      Hi moshe,

      “Error: console is not defined”

      Something was wrong and the debug method does not find a console to log it.

      Do you have a div with the unique ID “rating”?
      Where is the start number?: start: ,

  • Reda

    março 1st, 2011

    Responder

    Dear wbotelhos, thank you so much for your answer.

    i’m currently out of the country for a little while, i’ll try it very soon and will let you know.

    it’ll be really nice if we can use different image sizes…

    Regards,
    Reda

    • wbotelhos

      novembro 17th, 2011

      Responder

      Hi Reda,

      Now we can use the option size to do that.

  • Sean

    março 1st, 2011

    Responder

    Hi Wbotelhos,

    I love this plugin and I’m using 1.2.1 version, but I meet a problem when I need to refresh the start and score dynamically.

    In my page, I have one readonly raty (says: Raty1, half=true) plugin and a non-readonly raty (says: Raty2, half=false).

    When I click the Raty2 to vote, I will invoke a ajax action to do vote, after that, I will get average rating score from database and then update Raty1.

    But when I use $.fn.raty.start(score, ‘#Raty1′) to refresh the Raty1. NOTE here, score is a float numeric, and half attribute is true for Raty1.

    For example:
    After executed $.fn.raty.start(2.66, ‘#Raty1′), the Raty1 will be reset to 2 stars!! Not 2 and half stars, and the hint will be reset to DEFAULT hint???

    I don’t know whether it’s a bug?? Is it possible to fix?

    BTW: I used following codes to create Raty1:

    $('#Raty1").raty({
        readOnly: true,
        half: true,
        hintList: [null],
        noRatedMsg: 'Not voted this idea yet!',
        start: 2
    });
    
    • wbotelhos

      março 1st, 2011

      Responder

      Hi Sean,

      The problem is that public functions will take the last configuration used by Raty.
      I still have not found a way in jQuery plugins methods to retrieve the specific configuration of a bind. But I can do it manually. :(

      <div id="star1"></div>
      <div id="star2"></div>
      
      <script type="text/javascript">
          $(function() {
              $('#star1').raty({
                  half: true,
                  hintList: [null]
              });
      
              $('#star2').raty({
                  click: 	function(score) {
                      $.fn.raty.start(2.66, '#star1');
              }
          });
      
      });
      

      In this case the public function start will get the configuration of the bind of #star2, because it is the last and current configuration, not the first #star1.

      Could you open an issue for me for this problem?: https://github.com/wbotelhos/raty/issues/labels/1.3.0

      Thank you.

      • Sean

        março 4th, 2011

        Responder

        Wbotelhos,

        Thanks for your answer, I have opened one issue at github.

        Look forward to you can find a way to fix it soon :-)

  • Reda

    fevereiro 24th, 2011

    Responder

    Thank you very much for the fast answer!
    “1 – You can you the public function start like this: $.fn.raty.start(2, ‘#star’);”
    Well, it’s almost the same as $(‘#star’).raty({ start: 2 });
    what I would like to do is to be able to mention the score in the middle of my page by using this syntax:
    is that possible??

    “2 – You can use jQuery to check the value of the score input:”
    Thank you, i’ll tty it and will let you know

    3- is it possible to display 2 different sizes of the stars image (small and big)?

    Thanks a lot,
    Regards

    • wbotelhos

      fevereiro 24th, 2011

      Responder

      Hi Reda,

      1 -
      All public functions are made to be used in the middle of the code.
      $(‘#star’).raty({ start: 2 }); is used just one time, since the public functions is used many times as you want during your code.

      3 – You can, but you’ll need to ajust some calculations code at line 119, 120 and 205 if I’m not wrong.

  • Reda

    fevereiro 23rd, 2011

    Responder

    Hi, and thank you so much for this nice plugin!
    I have please 2 questions if you don’t mind:
    1- is it possible to set a score directly in the div of stars?? for example

    2- I’ll have to use the rating with a small text area, how can i check if a rating has been set before submitting the form??

    thank you so much for your help
    Regards

    • wbotelhos

      fevereiro 24th, 2011

      Responder

      Hi Reda,

      1 – You can you the public function start like this: $.fn.raty.start(2, ‘#star’);

      2 – You can use jQuery to check the value of the score input:

      var score = $('#default').find('input[name="score"]').val();
      
      if (score == 0) {
          alert('You must to vote!');
      } else {
          alert('Sending the vote...');
      }
      
  • Grad

    fevereiro 22nd, 2011

    Responder

    i don’t know if you received me last mail, but i figured out how to fix my problem. Thanks for your help, and i offer you a coffee with pleasure ;)
    Bye

  • Grad

    fevereiro 22nd, 2011

    Responder

    Hi wbotelhos,
    first congrats for the plugin, i really like it !
    i had a query for you : once i wrote the score in my database, i would like to come back to the “average” score. And i don’t really know how i can show the average number from my database with “the stars” : like if the average is (6/10), i would like to show 6 stars. Can you please help me doing that?

    Thanks a lot

    • wbotelhos

      fevereiro 22nd, 2011

      Responder

      Hi Grad,

      You can simply check the values in the database and then perform the function .start() at the end of your callback to set it:

      onClick: function(score) {
          var id = this.attr('id');
      
          $.ajax({
              url: '/get/average',
              success: function(average) {
                  $.fn.raty.start(average, '#' + id);
              }
          });
      }
      
  • Alagappan

    janeiro 24th, 2011

    Responder

    Hi,

    Thanks for the help. I just fixed the error.

  • anonymous

    janeiro 21st, 2011

    Responder

    hi wbotelhos,

    In your rating star plug in whenever the mouse leaves the stars rating becomes zero eventhough i set the start value to 2

    But i want the default rating(i.e 2) to be displayed.

    how to make this happen?

    please sove this problem

    • wbotelhos

      janeiro 25th, 2011

      Responder

      Hi Anonymous,

      Check if you are not using ID repeated.
      And please, read the comments, other people have passed through the same situation.

  • Richard Starr

    janeiro 20th, 2011

    Responder

    Hi

    Love the script, nice one. Got a question though.

    How do i tie a raty to an item? So if i have several items on a page and would like to have users rate each one individually, how do i pass an itemId to the script along with the score for processing?

    Regards

    Richard

    • wbotelhos

      janeiro 20th, 2011

      Responder

      Hi Richard,

      When you have several items, you must use Raty by class: With a group of element.

      During the processing, Raty get each element by the class and if it element has no ID, then one is created for it.
      When you are using Raty by the class, you do not have to specify an ID for each element, it’s optional. This is to ensure the IDs are not repeated.

      Inside the onClick callback you can retrieve this ID using this.attr('id');

  • Alagappan

    janeiro 20th, 2011

    Responder

    Hi,

    Can you help me with the query that I had asked earlier. I have posted the code in my previous comment here.
    Thanks. :)

    • wbotelhos

      janeiro 20th, 2011

      Responder

      Hi Alagappan,

      Sorry for forgetting your comment.

      I tested the first block of code and seems to be ok.
      Tested individually and also the following lines is okay:

      $. fn.raty.start (date, '# rateplugin');
      $. fn.raty.readOnly (true, '# rateplugin');
      $ ('# ratingmsg'). html ('Average Rating');
      

      - Make sure there is only one element with the ID ‘rateplugin‘ and only one with ID ‘ratingmsg‘;
      - Use the name ‘post‘ in lowercase, this is the correct way by the W3C;
      - Test the value of ‘data’ here: alert(data);.

      The second block also seems ok either.

      $.fn.raty.start(score, '#rateplugin');
      

      You can try to change the ID name handwritten by the captured dynamically:

      $. fn.raty.readOnly(true, '#' + this.attr('id'));
      

      Check with Firebug if the score was setted to the hidden field within Raty, because when the mouse out this value is captured to restore the value of Raty.

      <input type="hidden" id="rateplugin-score" name="score" value="2">
      

      Make sure all the codes that doesn’t belong the Raty are running properly and check again the ID, because in your case you could have only one element with the ID ‘rateplugin‘.

  • Diogo

    janeiro 16th, 2011

    Responder

    Pois então cara, não sei o que é, eu estou gerando dinamicamente via PHP, não entendi direito o problema, acredito que não seja o caminho das imagens pois as estrelas aparecem normalmente…

    Estava aparecendo um campo de texto com o valor do score, alterei os inputs para tag “a” e ficou omitido.

    Valeu.

  • Diogo

    janeiro 16th, 2011

    Responder

    Opa Washingtom beleza?
    Bem legal seu plugin, coloquei ele num sistema e rodou legal, só teve um problema, ficou aparecendo um label com o valor do rate, solucionei trocando todos os “input” do script por “a” e ficou certinho.

    Abraço.

    • wbotelhos

      janeiro 16th, 2011

      Responder

      Oi Diogo,

      Teria como me explicar melhor? Só existe um input que é hidden e guarda o resultado da avaliação.
      No mais são tags <img/> que se não for encontrado o caminho da imagem apresenta um texto com o número correspondente da estrela.

      Não seria esse o “label” que você fala?
      Se for o problema é o caminho da imagem, pois se não achar o texto alternativo é apresentado no lugar.

  • surya

    janeiro 11th, 2011

    Responder

    Hi,

    I have to use a .net server control for some reason. the server control is rendered as below:

    As you can see the value is also being rendered. Is there any way I can hide that input tag which appears next to the stars.

    • wbotelhos

      janeiro 26th, 2011

      Responder

      Hi Surya,

      I didn’t understand what input you talking about.

  • surya

    janeiro 11th, 2011

    Responder

    Hi,

    I am calling the rating plugin as below.

    $(function() {
        $('a.ratingBar').each(function() {
            var $this = $(this);
    
            $this.raty({
                start:		$this.attr('value'),
                onClick:	function(score) {
    
                   //call server method
                }
            });
        });
    
    });
    

    Problem is I can see one input box next to the stars and also on mouse over/mouse out all the stars are replaced with empty stars.
    Please tell me how to solve this.

    • wbotelhos

      janeiro 11th, 2011

      Responder

      Hi Surya,

      You must use <div/> or <span/> not <a/>: $(a.ratingBar).
      The element </a> don’t have the attribute value: $this.attr(‘value‘); and the Raty don’t use it.

      You can use this example: http://www.wbotelhos.com/raty/index.html#group-demo

      Or with each getting a attribute value like this:

      <div id="1" class="raty-class"></div>
      <div id="2" class="raty-class"></div>
      <div id="3" class="raty-class"></div>
      
      $(function() {
      
          $('div.raty-class').each(function() {
              var $this = $(this);
      
              $this.raty({
                  start: $this.attr('id'),
                  onClick: function(score) {
                      alert(score);
                  }
              });
          });
      });
      
  • Alagappan

    janeiro 11th, 2011

    Responder

    Hi,

    This is the code that I use for my site. The first script is used to store the value once the user selects some rating and then display the average rating.
    The second script is the one which I use when the page loads for the first time. This is where it fetches the average rating to show at the start. But when the user hovers on it and moves away the ratings are reset to 0. Please suggest a solution.

    $(document).ready(function(){
           var pathname = window.location.pathname;
        $('#rateplugin').raty({
           onClick: function(score){
           var dataString = 'pathname='+pathname+'&score='+score;
    
            $.ajax({
            type: "POST",
            url: "/storestar/",
            dataType: "text",
            data: dataString,
            success: function(data){
             $.fn.raty.start(data, '#rateplugin');
             $.fn.raty.readOnly(true, '#rateplugin');
            $('#ratingmsg').html("Average Rating");
                }
             });
          }
        });
    });
    

    and

    $(document).ready(function(){
        var pathname = window.location.pathname;
        var dataString = 'pathname='+pathname;
        $.ajax({
        type: "POST",
        url: "/getavg/",
        dataType:"text",
        data: dataString,
        success: function(score) {
             $.fn.raty.start(score, '#rateplugin');
        }
    });
    });
    
  • san

    janeiro 10th, 2011

    Responder

    Thanks, that helped.

  • Alagappan

    janeiro 10th, 2011

    Responder

    Hi,

    I use this plugin to display rating on my website. When the page loads, I fetch the existing average rating and display it using the start option. But when the use hovers on the stars the existing rating disappears and when the mouse moves away from the stars it shows empty stars.
    What can I do in that case?

    • wbotelhos

      janeiro 10th, 2011

      Responder

      Hi Alagappan,

      Are you repeating ID?
      Please, show me the plugin code for me debug it.
      Raty can work with multiple elements at once without problems.

  • sandeep

    janeiro 7th, 2011

    Responder

    Hi,

    I am using this pulgin to provide rating inside dot net List-view control. The ‘rating’ needs to appear for each record in the listview. I am using the below code for achieving it.

    Code:

     function DisplayRatings() {
                $('DIV.ratingBar').each(function() {
                    var id = $(this).attr('id');
                    var count = $(this).attr('rel');
                    $('#' + id).raty({
                        showCancel: false,
                        readOnly: false,
                        showHalf: true,
                        start: count,
                        onClick: function(score) {
                            //SaveRating(id, score);
                            alert("In");
                        }
                    });
                });
     }
    

    Problem is, If i rate once and immediately rate again the onClick fires twice. It increases based on the number of times I rate
    I.e first time i click onClick fires once, second time it fires twice, 3rd time thrice. Expected behavior is for each click onClick event should fire once. Please let me know what I am doing wrong here and how can I solve this.

    Thanks

    • wbotelhos

      janeiro 9th, 2011

      Responder

      Hi sandeep,

      Don’t put the Raty within a function. It’s should stay within the ready tag to be applied just once.
      If you call the function more than once, the bind will be doubled and it will fire twice or more.

      You should do this:

      $(function() {
          $('div.ratingBar').each(function() {
              var $this = $(this);
      
              $this.raty({
                  showHalf:	true,
                  start:		$this.attr('rel'),
                  onClick:	function(score) {
                      //SaveRating($this.attr('id'), score);
                      alert('Applied only once.');
                  }
              });
          });
      
      });
      
  • Fanatic

    janeiro 6th, 2011

    Responder

    Alright, good to know, and yes you should consider it, WordPress is a great platform.

  • Fanatic

    janeiro 5th, 2011

    Responder

    Just wondering, if there was a Worpdress version of your plugin?

    • wbotelhos

      janeiro 5th, 2011

      Responder

      Hi Fanatic,

      Unfortunately not, but it is an idea which already thought.
      Perhaps in future I try to create it.

  • marcela

    novembro 26th, 2010

    Responder

    Thanks!! thanks!!!…. yes! now works.

  • marcela

    novembro 25th, 2010

    Responder

    ohoh!

    dear, I did what you said but still does not work

    :’(

    thanks for your help!

    • wbotelhos

      novembro 25th, 2010

      Responder

      Hi Marcela,

      The div ‘infowindow’ which contains the ‘fixed’ exists only after you click on icon, and you should call Raty after the click.

      “The div must exist in the DOM to the Raty works!”

      Open the ‘infowindow’ balloon to be created the ‘fixed’ div and run this in FireFox console:

      $('#fixed').raty({
          path: 'http://wbotelhos.com/raty/img'
      });
      
  • marcela

    novembro 25th, 2010

    Responder

    I implement jquery-Raty with Google-maps. v3
    I need to add score to the marks, add the line:
    $ (“# Fixed”). Raty ({
    readOnly: true,
    start: 2
    });
    And where I want to leave the score is on InfoWindow and added:
    But it works! Shows nothing. Please help
    see here http://planosunab.mentalidadweb.com/?page_id=33

    • wbotelhos

      novembro 25th, 2010

      Responder

      Hi Marcela,

      You have two divs with id ‘fixed’, remove one;
      Put the path of the images in Raty;
      Place the code inside a ready function, because the div must exists before of the Raty execute:

      $(function() {
          $('#fixed').raty({
              path: 'your-image-path'
          });
      });
      
  • Arwo [PL]

    novembro 24th, 2010

    Responder

    HA! I’ve got an solution for my problem.

    You need to clear a content and unbind an raty event :)

    $(‘#YOUR_DIV’).html(”).unbind().raty();

    It’s the reset of stars in raty div.

    • wbotelhos

      novembro 24th, 2010

      Responder

      Hi Arwo,

      The correct way to do this in this case is $.fn.raty.start(0, '#your-div');

      * Use empty() not html('').

  • Arwo [PL]

    novembro 24th, 2010

    Responder

    Hi.

    How can I reset starts to zero, just the same as Cancel Button?

    What I want to do?
    After rating once by customer I would like to reset stars, that the same customer could do it again.

  • Alexander Hupe

    novembro 18th, 2010

    Responder

    Hi,

    thank you. But the Problem is, the Ids are not 1,2,3 etc. The IDs are depending on which product the customer has purchased.

    the Result must be e.g.:

    name=”rating[4512]”
    name=”rating[8874]”
    name=”rating[1236]”

    for an other customer are the rating:

    name=”rating[123]”
    name=”rating[66666]”
    name=”rating[76533]”

    I think, the best way was:

    what do you mean?

    Alex

    • wbotelhos

      novembro 18th, 2010

      Responder

      Hi Alexander,

      Your code doesn’t appeared.
      But in the each function you can change what you want in Raty.

  • Alexander Hupe

    novembro 17th, 2010

    Responder

    Hi,

    I just found your brilliant script. Now I have a a little problem:

    Within a form, several random products will be evaluated (using a foreach loop). Therefore, the score-name be changed dynamically and should be an array.

    Here an example:

    article1:
    (should have the score name: rating[articleID_1] )

    article2:
    (should have the score name: rating[articleID_2] )

    article3:
    (should have the score name: rating[articleID_3] )

    BUTTON: RATE

    Can you help?

    • wbotelhos

      novembro 17th, 2010

      Responder

      Hi Alexander,

      You can change the name of the score by jQuery like this:

      $('.rating').each(function(i) {
          $(this).raty()
      	    .children('input[name="score"]')
                  .attr('name', 'rating[articleID_' + (i + 1) + ']');
      });
      

      Result:
      name="rating[articleID_1]"
      name="rating[articleID_2]"
      name="rating[articleID_3]"

  • Guillermo

    novembro 14th, 2010

    Responder

    Thanks you, actually!

  • wbotelhos

    novembro 14th, 2010

    Responder

    Hi @Guillermo,

    This feature was released in version 0.9: Improved the selector to accept bind by class name.

    Thanks.

  • Guillermo

    novembro 4th, 2010

    Responder

    Great. I got it working.

    I thought about dinamic id… but this also works:

    $(".rating").each(function(index) {
        estrellas = $(this);
    
        estrellas.raty({
        ...
    }
    

    Obrigado!

    As i have 12 object to rate, i’m printing the points of each one in a html tag, and taking them from there with that loop. That works perfectly also. Btw, i’m using avg() method from mysql to calculate the points…

    Cheers!
    Mayid

  • Jürgen

    novembro 4th, 2010

    Responder

    oh, I see. Is there a fast way to provide that functionality?

    • wbotelhos

      novembro 4th, 2010

      Responder

      Well Jurgen,

      You can change the star icon to half icon, reduce the area of each icon to keep the half star and add the space between them only every two half icons.

      I think the most difficulty would be get the score, since every odd value will be worth 0.5.
      I just did not make this feature, because I think the users don’t worry about this precision and it’s a kind weird design, leaving only the result displaying half stars, because there is no way to avoid decimal values in the average.

      Later I can give you a better brief.

  • Jürgen

    novembro 4th, 2010

    Responder

    Hello, I really like your rating script!
    I have only one problem with it: After using $.fn.raty.start(some_value); I cannot do half-star-ratings? Is there a way to fix it?

    I am using it in such a way:
    First static initialization:

    	$('#half').raty({
    	  start:    0,
    	  showHalf:  true,
    	  onClick: function(score) {
    		 $.ajax({
    	     	   type: "POST",
    	     	   url: "rate.action",
    	     	   data: wgaId="+document.getElementById('wgaId').value+"&amp;userRating="+score
    
    	     	 });
    		  }
    	});
    

    I have an image site and when the image is changed by the user, I have to refresh also the rating. Therefore I make the following ajax call.

    $.ajax({
            type: "POST",
            url: "getRating.action",
            data: "wgaId="+wgaid,
            targets:  "ratingDiv",
       success: function(msg){
                $.fn.raty.start(msg);
             }
     });
    

    The problem is, that after setting the new value of the rating with $.fn.raty.start(msg); the users can’t make half-star-ratings anymore.

    • wbotelhos

      novembro 4th, 2010

      Responder

      Hi Jurgen,

      The Raty just display half start based on the score (average). It does not give you the option of select half star.
      You are only able to set using the attibute start or the public function $.fn.raty.start(x), but you can’t click and do it, then it’s just show half star and not pick it.

  • Guillermo

    novembro 3rd, 2010

    Responder

    Can this be used with several objects to rate? I mean, an image gallery by example. Your selector points just one object.

    I tried applying this with a class name, and even using an .each loop but i can’t make it work.

    By other hand, the browser keeps throwing this error:
    Uncaught Syntax error, unrecognized expression: .

    Any clue?

    • wbotelhos

      novembro 3rd, 2010

      Responder

      The Raty is applied on an element at a time according to the ID, but that does not prevent you to create the element and then immediately apply or use a continuous ID and then iterate over these later:

      <div id="raty-0"></div>
      <div id="raty-1"></div>
      <div id="raty-2"></div>
      
      for (var i = 0; i < 3; i++) {
          $('#raty-' + i).raty();
      }
      

      Normally the elements are dynamically created, but if you already have the divs created statically, then you must apply a raty() for each one. See that the best way to use the Raty is using a continuous ID, so you can iterate over these divs to apply it.

      I’ll see a way to apply the according to a class in future versions.

  • Farouk Alhassan

    outubro 24th, 2010

    Responder

    Hi,
    I have created an issue here
    http://github.com/wbotelhos/raty/issues/#issue/2

    Which is something to do with the hints breaking subsequent ratings.

    I have created a set of icons that are much nicer and also have one-third, half and two-thirds versions. Let me know if you are interested and i can send them to u

    Regards
    Farouk A

    • wbotelhos

      outubro 24th, 2010

      Responder

      Hi Farouk,

      The Issue that you opened will be solved in version 0.7 in next week, which were also solved other problems and will be lighter too. As for the icon if you want just send me, maybe we can put them in the example of customization icons.

      Any help will be welcome. (:
      Thank you.

  • charlie T

    agosto 11th, 2010

    Responder

    change global $this=$(this) to “var $this=$(this) ” fixes the problem you have with only last raty recognized. I also removed “live” for mouseenter and leave. Can email a copy if interested

    • wbotelhos

      agosto 11th, 2010

      Responder

      Hi Charlie,

      Can you explain better the bug?
      I used the global $this because it’s needed into the another functions scope like liveClick() and initialize().
      You’ve changed the live to bind or something or you are talking about of public functions?

      I’ll be happy to receive your script for information.

Leave a Comment

* are Required fields