Javascript tag clouds

By Korvin on Mar 07, 2010


var arr = Array('that','that','that','test','test','this','this','this','this');

that is the screenshot.

go ahead and change the maxsize and minsize according their obvious respective values.
also easy to edit styles:

end+="<span style='font-size:"+s+"'>"+r+"</span>";

can become any style you want. ex:

end+="<ul><li style='font-size:"+s+";color:#333;' onmouseover='\"#cc0000\"' onmouseout='\"#333\"'>"+r+"</li></ul>";

Live Hawkee Looking Example

as ie doesnt support foreach, you need have to include this:

if (!Array.prototype.forEach)
  Array.prototype.forEach = function(fun /*, thisp*/)
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
      if (i in this), this[i], i, this);

^^code from Mozilla Development Center

function tagCloud(tags) {
    //set max font-size
    var maxsize = 44;
    //set min font-size
    var minsize = 9;
    //preset variables as to create no confusion
    var tag=new Array(), ta=new Array();
    var cloud='', h=0, val=0, i=0;
    //proccess given tag array
    //counting the accurances of tags
        //current tag has already been recognized
        if (tag[t]) {tag[t]++;}
        //current tag hasn't been recognized
    //find the highest amount of tag accurances in the form of a number
    //if the current tag count is higher than the current highest, it is the current highest.
        if (tag[g] > h) {h=tag[g];}
    val=(maxsize/h);//get the font-size interval needed to vary sizes
    ta.forEach(function(r){//set the size of the current tag by multiplying the interval by the amount of times the tag is used.
        //set the size, if it is smaller than the minimum font-size, it is the minimum font-size.
        var s=(Math.round(val*tag[r])>minsize) ? Math.round(val*tag[r]) : minsize;
        //concatenate finished styled tag into cloud
        cloud+="<span style='font-size:"+s+"'>"+r+"</span>";
    //return cloud.
    return cloud;


Sign in to comment.
Korvin   -  Mar 08, 2010


owl   -  Mar 08, 2010

Very nice, just the other day I was using CSS to size them all, I shall now change it to this :D

Hawkee   -  Mar 08, 2010

Check the large comment in the code, it explains how it works.

Korvin   -  Mar 08, 2010

Can u explain that?

Hawkee   -  Mar 08, 2010

That's a different method from what I've seen. I used a bucket method here:

Korvin   -  Mar 07, 2010

ill make the code more readable.

Hawkee   -  Mar 07, 2010

What sort of logic did you use to divide up the font sizes among the tags?

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.