Rating with stars (jQuery, CSS, Django)

Here is some code I wrote to have an arbitrary number of stars (such as five) rate items. The jQuery code responds to mouseover events and mouse click events by changing the look of the stars and passing the rating to the server by visiting a URL. To see them in action, visit www.momsrobot.com/beta and rate some links!

Here is the jQuery. It uses some Django template stuff. It was written under jQuery 1.4 but is pretty simple, so should work under different versions.

    <script type="text/javascript" src="/static/jquery-1.4.js"></script>
    <script type="text/javascript">
      $(function() {
        $('.star').click(function(){
          $(this).addClass('on rating');
          $(this).prevAll().addClass('on rating');
          $(this).nextAll().removeClass('on rating');  
          //	How to select the parent div of 'this'?
          $(this).parent().addClass('rated');
          var hit_id = $(this).parent().attr('id');
          var rating = $(this).siblings().add(this).filter('.rating').length
          $.post("/rate/", {user: "dennis", rating: rating, id: hit_id}, 
            function(data) {
              // alert(data);
            });
        });
      });

      $(function() {
        $('.star').hover(
          function(){
            $(this).addClass('on');
            $(this).prevAll().addClass('on');
            $(this).nextAll().removeClass('on');
          },
          function(){
            $(this).siblings().add(this).removeClass('on');
            $(this).siblings().add(this).filter('.rating').addClass('on');
          }
        );
      });
    </script>
<script type="text/javascript">

As you can see, the jQuery code works by manipulating the DOM. It works in conjunction with the following Django template code and CSS. The Django template stuff could easily be adapted to other frameworks. To change the number of stars, change the number of div’s. To change the initial rating, change the “on rating” class members.

<div class="rating" id="{{item.pk}}">
  <div class="star on rating"></div>
  <div class="star on rating"></div>	
  <div class="star on rating"></div>	
  <div class="star"></div>	
  <div class="star"></div>
<div class="userrating" id="{{item.pk}}"></div> 
</div>

And here is the CSS. You’ll need to provide your own star .png images! I found mine in the public domain.

.star {
     width:29px;
     height: 29px;
     background-image:url(white_star.png);
     float:left;
}

.on {
     background-image:url(yellow_star2.png);
}

.rated &gt; .rating {
     background-image:url(red_star.png);
}

With the code so far working together, you’ll have some stars that light up and change colors. This code talks to your serverside code through this line:

$.post("/rate/", {user: "{{ username }}", rating: rating, id: hit_id}

The username, rating, and id (of whatever is being rated) is posted to the URL /rate. You set up your serverside code to process whatever is posted to /rate. Like so:

def rate(request):
    if request.is_ajax():
        if request.method == 'GET':
            message = "fail"
        elif request.method == 'POST':
            user = request.POST.get('user')
            rating = request.POST.get('rating')
            this_id = request.POST.get('id')
            message = str(user) + " "+ str(rating) + " " +str(id)
    else:
        message = "No XHR"
    # do something
    return HttpResponse(message)

Of course you’d need to set your urls.py to pass /rate POST data to this function. I hope this code helps you.

Advertisements

One thought on “Rating with stars (jQuery, CSS, Django)

  1. human mathematics says:

    I didn’t tell you this but I have a long rant against the 1-to-5-stars system. Posets. Posets are where it’s at.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: