Official website for Web Designer - defining the internet through beautiful design
FOLLOW US ON:
Author: Steve Jenkins
29th December 2012

Create a star-rating gallery system with jQuery

Add a jQuery star rating system to your image galleries and let your users rate the images.

Create a star-rating gallery system with jQuery

There are countless free image gallery scripts available on the web, whether it’s using the Flickr photostream, or downloading and installing a script directly on to your web server.
These solutions are great for basic implementations, but they tend to look very similar once they’ve been deployed to your site. Instead of following the crowd and going for an off-the-shelf solution, why not use the power of jQuery to create your own unique image gallery? This tutorial shows you exactly how to do this, and although you’ll need an understanding of how JavaScript works, it’s surprisingly easy to achieve a polished result that will help make your website stand out from the identikit galleries that populate the world wide web.
We’re going for a tablet-inspired theme to position our gallery on the page, but as you follow along you’ll get the skills necessary to theme your own gallery to suit your site.

DOWNLOAD FULL CODE

Sketch it out

Create a star-rating gallery system with jQuery
The first step when embarking on a project like this is to sketch out your ideas, getting a grip on what functionality you’d like to incorporate, how the user will interact with your gallery, and at least an idea of the visual approach you’d like to take. Spend five minutes with your sketch pad or a scrap of paper to work out the basics first!

Create an XML file

As we are already at the command line, we might as well set up our initial project while we are here. After entering the following command, a skeleton ZURB project will be set up. Ensure you are at the folder you store your local site builds (eg I use ~/Sites) and run the following command where foundation3 is the name of the project/folder you want creating:

Add gallery HTML

Create a star-rating gallery system with jQuery
Now we’ve got our gallery source materials, it’s time to create the basic HTML document that will display our images. We’ve provided a simple start document on the resource disc you can use as a basis for this. Add the code to create the HTML elements we’ll need to display our gallery and star ratings.

Only include what you need

Before we can show the images, we need to load our XML file using jQuery. If you don’t have it, grab jQuery from www.jquery.com and insert it at the top of your page, then create a script to hold your own jQuery and add the code shown to load the XML, ready for use by JavaScript.

Add paging buttons

Our XML document has multiple images, so add the code below inside the setupImages() function to create two anchors that will allow movement through the gallery to the previous and next image. We’ve already set up the CSS styles for these anchors, so the script will just add them to the page.

001 // Add forward/prev buttons
002
003 var newhtml = “<      a title=\”move to previous image\” id=\”prev\”><      /a><      a title=\”move to next image\” id=\”next\”><      /a>”;
004
005 $(“#containerinner”).append(newhtml);

Make ‘em work

When we click on the previous button the script needs to look at the XML document and grab the details for the previous image. It will then show this in place of the existing image. If there is no previous image, it will show the last image, allowing the user to move through the gallery in a loop. The next button will work in the same way but in reverse. Add the code below to give this behaviour to the buttons.

001  // Add click events to prev and next
buttons
002
003 $(“#prev”).click(function(){
004
005    var tmp = $(currentimage).prev();
006
007    if ($(tmp).find(“path”).text()==”") {
008
009        currentimage = $(xmlData).
find(“image:last”);
010    } else {
011
012        currentimage = tmp;
013
014    }
015
016    showNewImage();
017 });
018
019 $(“#next”).click(function(){
020
021    var tmp = $(currentimage).next();
022    if ($(tmp).find(“path”).text()==”") {
023
024         currentimage = $(xmlData).
find(“image:first”);
025     } else {
026
027        currentimage = tmp;
028
029    }
030
031    showNewImage();
032
033 });

Rating scores

Each image has a rating score. We could have used separate graphics for each star in the score, but for ease we’ve created two graphics – one with empty stars and one with full stars. We’ll overlay them so they match perfectly and adjust the width of the full stars div to only show a certain score. This is easiest to understand by looking at the diagram!

Display the score

Add the code below to convert the score from the XML sheet using the overlaid stars. The first star starts at 50px in from the left, and each star occupies 40px of width, so we multiply the score by 40px and add 50px, then set the width of the stars’ overlay to the result – hey presto, we have our score.

User scoring

We can allow the user to submit their rating by clicking on the stars. As the user moves their mouse over the stars we want to illuminate the stars to indicate the score that will be submitted, so add the code below to do this. As we only want to allow whole numbers in the submitted score, we’ll check where the mouse is and use that to illuminate whole stars.

001 $(“#starbg”).mousemove(function(e){
002    // limit stars to move in whole stars
003    // Get offset of element on page
004    var offset = $(this).offset();
005    // get mouse position relative to stars
006    var position = e.pageX – parseInt(offset.
left);
007
008    var starwidth = (parseInt((positi
on-50)/40)+1)*40+50;
009            $(“#stars”).css({width:starwidth});
010
011    }).mouseout(function(){
012
013 // reset stars to current voting score
014
015 $(“#stars”).css({width:starwidth});
016
017 }).click(function(){
018    newscore = parseInt($(“#stars”).
css(“width”));
019
020    var tmpscore =
(parseInt((newscore-50)/40));
021 $(“#instructions”).html(“Thanks for your
rating!”);
022
023        });

Calculate the submitted score

We need to use the same criteria to calculate the submitted score as we used to limit the display to whole stars. Add the code below to your script to check the width of the stars element and use that to calculate the score submitted by the user.

001 $totalColumns: 24;
002 $mobileTotalColumns: 8;

Do the math

The score is the sum of all submitted votes divided by the number of votes. For ease, we’ll round the score to 2 decimal places which prevents silly scores such as 3.1415926536! Add the code shown to calculate the new score and update the stars so they show it on screen.

Add some finesse

Create a star-rating gallery system with jQuery
We can add some final flourishes to our script and the visual effect by animating a few properties. Let’s start off by designing an animation to be shown while the images first load. Open up Photoshop and use the timeline to animate three discs from 0% to 100% Opacity. Save this as an animated GIF and add to your placeholder div as the background.

Slide up text

As well as the animation during loading, after each image has been shown we could animate the caption into place instead of simply allowing it to sit on top of the image. Add the code shown to do this for WebKit-based browsers, and apply the same approach for other browsers if desired. The code for this step can be found on the resource disc.

Activate the animation

Create a star-rating gallery system with jQuery
The final thing we need to do is to add the active class to the image label once the new image has been shown. This will trigger the animation once. To make it trigger again, we need to also remove the class when switching between images. Add the code shown to complete the effect and the script.

001  // Display the image, caption, rating and label
002    function showNewImage() {
003    var image = $(currentimage).find(“path”).
text();
004        var caption = $(currentimage).
find(“caption”).text();
005        score = parseFloat($(currentimage).
find(“rating”).text());
006        numvotes = parseInt($(currentimage).
find(“numvotes”).text());
007        starwidth = parseInt(score*40)+50;
008        $(“#stars”).css({width:starwidth});
009        $(“#imagelabel”).removeClass(“active”);
010        // Fade out current image and fade in
new image
011        $(“#imageplaceholder”).
animate({opacity:0},500, function(){
012 $(this).css({“backgroundImage”:”url(“+ima
ge+”)”}).animate({opacity:1},500, function(){
013                $(“#imagelabel”).addClass(“active”);
014            });
015        });
016        // Add caption
017        $(“#imagelabel”).text(caption);
018        // Check to see if voting has happened
on this image
019        if ($(currentimage).find(“hasvoted”).
text()==”false”) {
020            $(“#instructions”).html(“Click to rate this image”);
021        } else {
022            $(“#instructions”).html(“You
previously rated this image”);
023        }
024    }

Test and review

The final step is perhaps the most important of all – testing and reviewing your script obsessively. You need to make sure that the PHP is updating your XML correctly, that images are loading and displaying as they should, and that all browsers render your gallery in the correct manner.

  • Tell a Friend
  • Follow our Twitter to find out about all the latest web development, news, reviews, previews, interviews, features and a whole more.