Search code examples
jqueryhtmlpluginsradio-buttonrating

Alternative jquery rating plugin?



The title is not very illustrating, but I'll try to explain.

I'm looking for a jquery rating plugin which behaves like a standard star rating, but supports different images and colors depending on the selected value

For example, on the scale of 1-10:

  • 1-3 when hovered or selected all images/colors are red
  • 4-7 when hovered or selected all images/colors are yellow
  • 8-10 when hovered or selected all images/colors are green

I found this and this. but they don't quite do what I'm looking for.

So if anyone knows if there is something out there will save me a lot of time for creating a new plugin.


Solution

  • Why not make your own? I've already built a little demo to show that it's possible: http://jsfiddle.net/s2zPW/18/.

    The code isn't that hard either:

    HTML:

    <ul class="rating"></ul>
    

    JavaScript:

    $.fn.reverse = function() {
        return this.pushStack(this.get().reverse(), arguments);
    };
    
    // create two new functions: prevALL and nextALL. they're very similar, hence this style.
    $.each(['prev', 'next'], function(unusedIndex, name) {
        $.fn[name + 'ALL'] = function(matchExpr) {
            // get all the elements in the body, including the body.
            var $all = $('body').find('*').andSelf();
    
            // slice the $all object according to which way we're looking
            $all = (name == 'prev') ? $all.slice(0, $all.index(this)).reverse() : $all.slice($all.index(this) + 1);
            // filter the matches if specified
            if (matchExpr) $all = $all.filter(matchExpr);
            return $all;
        };
    });
    
    for (var i = 0; i < 10; i++) {
        $('.rating').append('<li>' + i + '</li>');
    }
    
    $('.rating li').hover(function() {
        if ($(this).index() < 2) {
            $(this).prevALL('li').css('background-color', 'rgb(255, 160, 160)');
        } else if ($(this).index() < 4) {
            $(this).prevALL('li').css('background-color', 'rgb(255, 200, 200)');
        } else if ($(this).index() < 7) {
            $(this).prevALL('li').css('background-color', 'rgb(235, 220, 200)');
        } else if ($(this).index() < 10) {
            $(this).prevALL('li').css('background-color', 'rgb(200, 255, 200)');
        }
    }, function() {
        $(this).parent().children().css('background-color', 'rgb(200, 200, 200)');
    });