Search code examples
jqueryrating

jQuery star rating plugin that clears rating on rated star click?


This is baffling, but I can't seem to find a decent jQuery star rating plugin that clears the rating when you click on a rated star (as in: you rate 3 stars, you click the 3rd star again, and the rating is removed). I keep finding plugins that have that silly "clear rating" button to the left of the stars. When I was using prototype I was using ratingbox, which worked well, but I can't find a jQuery equivalent.

I would greatly appreciate any recommendations!


Solution

  • If you don't need any special functionality, you can use my code. Should be easy to convert it into a plugin if required.

    If you don't need the hover tracking effect, just remove the mouseenter and mouseleave events.

    The set rating is saved in a data attribute on the container div, you can access it via $('.rating').data('rating').

    Check out a live demo with some random images from the internet: http://jsfiddle.net/abPFF/1/

    HTML:

    <div class="rating" data-rating="3">
        <div></div><div></div><div></div><div></div><div></div>
    </div>
    

    CSS:

    .rating { display:inline-block; padding:0px; }
    .rating div { display:inline-block; width:48px; height:48px; margin:0px; background-image: url('star-off.png');}
    
    .selected { background-image: url('star.png') !important; }
    .highlighted { background-image: url('star.png') !important; }
    

    Javascript:

    function ShowRating($element, rating){
        $stars = $element.find('div');
        $stars.removeClass('selected highlighted');
        rating = parseInt(rating);
        if(rating < 1 || rating > $stars.length) return;
    
        $stars.eq(rating-1).addClass('selected')
            .prevAll().addClass('highlighted');
        return;
    }
    
    $('.rating').each(function(){
        var $this = $(this);
        ShowRating($this, $this.data('rating'));
    }).bind({
        mouseleave: function(){
            var $this = $(this);
            ShowRating($this, $this.data('rating'));
        }
    }).find('div').bind({
        mouseenter: function(){
            var $this = $(this);
            ShowRating($this.parent(), $this.index() + 1);
        },
        click: function(){
            var $this = $(this);
            var $parent = $this.parent();
            var idx = $this.index() + 1;
            if($parent.data('rating') == idx){
                // Remove rating
                ShowRating($parent, 0);
                $parent.data('rating', 0);
            } else {
                // Set rating
                ShowRating($parent, idx);
                $parent.data('rating', idx);
            }
        }
    });