jQuery: creating a tag cloud

In this post I'm going to show you how to create a dynamic tag cloud using jQuery and a few CSS rules. We want that each time the tag cloud loads have different link colors, with different font sizes and positioning. To accomplish this task, we'll create three helper functions that will generate random values for each CSS property used here. First, let's write our CSS:

#tag-cloud {
    padding: 0.5em 0;
    margin: 0.5em;
    width: 40%;
    list-style: none;
    font: 100% Arial, sans-serif;
    border: 1px solid gray;
    border-width: 1px 0 1px 0;
    line-height: 1.5;
}

#tag-cloud li {
  display: inline;
  text-transform: lowercase;
  padding: 0 1em;
}

#tag-cloud li a {
   text-decoration: none;
   position: relative;
}

As you can see, all list items are displayed inline. Further, each link has the declaration position: relative that will be used later for positioning. Now, the three helper functions:

function createRandomColor() { 

    var hex = '0123456789ABC'.split(''),
    color = '#', i; 

    for (i = 0; i < 6; i += 1) {
        color = color + hex[Math.floor(Math.random() * 13)];
    }  

    return color;
}

function setFontSize() {

    var maxFontSize = 30;
    var fontSize = Math.floor(Math.random() * maxFontSize + 14) + 'px';

    return fontSize;

}

function setOffsets() {

    var offsets = {};

    var randTop = Math.floor(Math.random() * 10);
    var randLeft = Math.floor(Math.random() * 10);

    var maxTop = Math.floor(Math.random() * randTop) + 'px';
    var maxLeft = Math.floor(Math.random() * randLeft) + 'px';

   offsets.top = maxTop;
   offsets.left = maxLeft;

   return offsets;    

}

The first function returns an hexadecimal value using the random() method of the Math object. Note that we've skipped the hexadecimal values D, E, and F from the array in order to prevent the function from returning colors with a too poor contrast.

The second function is similar to the first one, except that in this case returns a font size value expressed in pixels. Note how in this case we've set a minimum font size to 14 pixels in order to prevent this function from returning illegible values.

Finally, the third function uses the same routines and methods of the other functions, except that it returns an object literal containing the offsets of each link. Now we can put it all together:

$(document).ready(function() {

    $('#tag-cloud li').each(function() {

        var $a = $(this).find('a');
        var cssColor = createRandomColor();
        var cssFontSize = setFontSize();

        var linkOffsets = setOffsets();

        $a.css({color: cssColor, fontSize: cssFontSize, top: linkOffsets.top, left: linkOffsets.left});

    });

});

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.