jQuery Tag Cloud


In December 2011 I was working on a project to analyse the incoming stream of SMS messages into the BBC Radio studio. I created a tag cloud widget to display the most frequent words that were occurring in the SMS stream.

It's a pretty basic affair, but it is animated and looks ok.

To use it, you first need to include a few other javascript libraries. In particular, you require jQuery and the jQuery widget factory, but the code also uses jquery.timers (for its animation).

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="/js/jquery.timers-1.2.js"></script>
<script type="text/javascript" src="/js/TagCloudWidget-1.0.js"></script>

Create an element in the page and then apply the tag cloud widget to it, just as you would with any jQuery widget:

<div id="tagcloud"></div>
<script type="text/javascript">

You can use the setWords method to make the cloud display words. This method expects an associative array where the keys are the words and the values are the weight to apply to each word. The weight is a value between 0 and 1 which determines the scale of the word. The options provide the maximum and minimum sizes for any word in terms of percentage font size (which makes it scale with the browser font).

$('#tagcloud').tagcloud('setWords', { popular: 1, unpopular: 0.2 } );

The method setWordsAutoScale will automatically scale the frequencies of the words provides into the 0-1 range, so you don't have to do that yourself:

$('#tagcloud').tagcloud('setWordsAutoScale', { popular: 10, unpopular: 2 } );

As data is set into the tag cloud, tags that already exist are rescaled, while new tags are animated in and old tags, that no longer exist, are animated out.

Here's the code for that demo above. Note that sizes are generated randomly, but to ensure that some tags do not appear we are not adding them to the data if their size value is [purposely] too large. You can see that as tags come and go they are added and removed from the cloud.

// words array has been preset to a set of car manufacturers
$(document).everyTime( 2000, function()
	var data = new Array();
	for( w in words )
		// This ensures that some disappear now and again.
		var v = Math.random() * 1.5;
		if( v < 1 )
			data[words[w]] = v;
	$('#tagcloud').tagcloud( 'setWords', data );
}, 0 );

Also note that the example above has had its height fixed so that it doesn't make the page jump around.

The code is released under the MIT license, which basically means you can do whatever you like except pretend it's yours.