Thursday, April 19, 2012

How to duplicate rating information using javascript

As a response to the question from the previous post I'm going to explain how to duplicate rating information using JS callback function (in Blogger). So, what we want to do:
- show ratings below the posts (as usually);
- duplicate rating information and show it above the posts (without ability to vote).

Steps:

0. Make a backup copy of the template;

1. Open template editor (don't forget to select "Expand Widget Templates" checkbox);

2. Find ratings widget call and add parameter "callback=previewRating", something like this:
...class_star_vote=ffbs_star_aimg_vote&callback=previewRating&views=yes&average=yes...

3. At the desired place of the template write a div that will hold ratings duplicated information:
<div expr:id='&quot;graddit_preview_rating_&quot; + data:post.id'>Rating: </div>
for example, you can place it just before post body (before <data:post.body/>)

4. Somewhere (preferably on top) in your template write callback function, like this one:
<script language='javascript'>
function previewRating(key, id, stats, average, amount, votes, data, views) {
var div = document.getElementById("graddit_preview_rating_" + id);
if (div != null) {
var avg = Math.round(average);
var tmp = div.innerHTML;
for (var i = 0; i &lt; avg; i++) {
tmp += "<span class='ffbs_star_set'>&amp;#9733;</span>";
}
for (var i = avg; i &lt; amount; i++) {
tmp += "<span class='ffbs_star'>&amp;#9734;</span>";
}
div.innerHTML = tmp;
}
}
</script>

5. Save the template. You're done, ratings should be now showing right after title (before post body) of each post.

As you see, callback function is a powerful tool that gives you unlimited control over your ratings.

Reminder: the code above should be used with blogger templates only, it will not work with a different template system; you should adapt it to the templater or for pure HTML just remove redundant special characters. Let me know if you faced any problems with that.