6/25/08

Label cloud for blogger

I have nothing against Blogger's label widget, but I think label clouds are a better visualization for that matter. After searching around I came across phydeaux3 tag clouds. Based on that, I built my own widget for this blog. You can try it here. Type some words inside the box and click the 'create' button. You can also specify the colors you want for bigger and smaller words. Type them in hexadecimal format, without the # sign.


Big words color: #

Small words color: #


You can see the code on the source of this page (if you have javascript enabled, you'll see my label cloud on the sidebar. If not, you'll see the standard label widget). Or you can have the code here:

function cloudify(element_id, elements, options) {
  eReplace = $(element_id);
  var min_oc = null;
  var max_oc = null;
  var labels = elements;
  labels.each(function(e) {
    if(!max_oc || e[0] > max_oc){ max_oc = e[0] }
    if(!min_oc || e[0] < min_oc){ min_oc = e[0] }
  });
  if(min_oc == max_oc){ max_oc++ } // To prevent a divide by zero error
  var min_font_size = options['min_font_size'] || 10;
  var max_font_size = options['max_font_size'] || 30;
  var text = "";
  var log_min_oc = Math.log(min_oc);
  var log_max_oc = Math.log(max_oc);
  var log_diff = log_max_oc - log_min_oc;
  var start_color = stringToColorArray(options['start_color']||'B47B10');
  var end_color = stringToColorArray(options['end_color']||'006600');
  var link_start = "";
  var link_end = "";
  var link_href = function(e){return ""};
  if(options['includes_link']){
    link_start = "><a ";
    link_end = "</a>";
    link_href = function(e){return 'href="' + e[2] + '"'};
  }
  labels.each(function(label) {
    var w = (Math.log(label[0]) - log_min_oc) /(log_max_oc - log_min_oc);
    text = text + '<span' + link_start + ' style="font-size:' +
      String(min_font_size + Math.round((max_font_size - min_font_size) * w)) +
      'px; color:#' + 
      colorArrayToString([0, 1, 2].map(function(i){
        return start_color[i] + Math.round((end_color[i] - start_color[i]) * w);
      })) +
      '" ' + link_href(label) + '>' +
      label[1] + link_end + "</span> ";
  });
  eReplace.update(text);
}
Where elements is an array with element of the form [count, label] and a third element: the link of each label if specified in the options.

Anyway, is a very quick-and-dirty version, if you are interested on it and have troubles, drop a comment.

No comments: