May 10, 2008

A Simple Blogger Tag Cloud Widget

Here's a simple hack for a custom Blogger widget. This is the code for the simple tag cloud. Feel free to copy and modify the source as you see fit. It's a mix of JavaScript and Blogger Code, so it is only functional as a Blogger Widget.

Code:
<b:widget id='TagCloud' locked='false' title='Tags' type='Label'>
<b:includable id='main'>
<b:if cond='data:title'>
<h2><data:title/></h2>
</b:if>
<div class='widget-content' style='text-align: justify;'>
<script type="text/javascript">
//Variables:
var max = 150; //max css size (in percent)
var min = 50; //min css size (...)
var showCount = 1; // show counts? 1 for yes
var minCount = 1; // what is the minimum count for a Tag to be shown? 1 for all.

//Begin code:
var range = max - min;

//Build label Array
var labels = new Array();
<b:loop values='data:labels' var='label'>
labels.push("<data:label.name/>");
</b:loop>

//URLs
var urls = new Array();
<b:loop values='data:labels' var='label'>
urls.push("<data:label.url/>");
</b:loop>

//Counts
var counts = new Array();
<b:loop values='data:labels' var='label'>
counts.push("<data:label.count/>");
</b:loop>

//Number sort funtion (high to low)
function sortNumber(a, b)
{
return b - a;
}

//Make an independant copy of counts for sorting
var sorted = counts.slice();

//Find the largest tag count
var most = sorted.sort(sortNumber)[0];

//Begin HTML output
for (x in labels)
{
if(x != "peek" &amp;&amp; x != "forEach" &amp;&amp; counts[x] >= minCount)
{
//Calculate textSize
var textSize = min + Math.floor((counts[x]/most) * range);
//Show counts?
if(showCount == 1)
{
var count = "(" + counts[x] + ")";
}else{
var count = "";
}
//Output
document.write("<span style='font-size:" + textSize + "%'><a href='" + urls[x] + "'>" + labels[x] + count + "</a></span> " );
}
}
</script>
</div>
</b:includable>
</b:widget>


Installation:

If you already have a Labels page element installed, skip to step 2.

Step 1: Install the Labels page element by browsing to your template settings:



Click "Add a Page Element" in the column you wish:



Then find the Labels page element and click "Add to Blog":



Step 2: Replace the Labels page element widget code with the custom tag cloud code above.

First navigate to your templates source under your template settings:



Then check off "Expand Widget Templates":



Search for the Label page element you are replacing by searching for widget code. It will look something like this
<b:widget id='Label1' locked='false' title='Tags' type='Label'>
but id and title maybe different, so use your browser's search tool and look for type='Label'.

Delete the Label widget code from the start to the end marked by
</b:widget>
and replace with the custom Tag Cloud code from above.


0 comments:

Post a Comment