• Posted on October 24, 2013

JavaScript Tag Cloud

In a previous tutorial we made a PHP Tag Cloud generator function. But, some people don’t have access to PHP or need the tag cloud to update live using ajax or other means. Below is the JavaScript function and code. The code is fairly similar to the PHP Code, but just modified slightly for use with JavaScript. You call the function by identifying the DOM which all the words are listed in, and you also have to specify the Node Name, such as span or div.

Each Node Name that you specify requires a data variable of “count”, which is the occurrence of that word. Also in the main DOM, you need to specify the minfont and maxfont data variables for the font sizes. An example will be shown below.

function tagcloud(dom,tag) {
	var highVal = 0;
	var lowVal = Number.MAX_VALUE;
	var elements = dom.getElementsByTagName(tag);
	var minFont = parseInt(dom.getAttribute('data-minfont'),10);
	var maxFont = parseInt(dom.getAttribute('data-maxfont'),10);
	var fontDif = 0;
	var sizeDif = 0;
	var size = 0;
	var i = 0;
	var data = 0;

	for(i = 0; i < elements.length; ++i) {
		data = parseInt(elements[i].getAttribute('data-count'),10);
		if(data > highVal) {
			highVal = data;
		}
		if(data < lowVal) {
			lowVal = data;
		}
	}

	fontDif = maxFont - minFont;
	sizeDif = highVal - lowVal;

	for(i = 0; i < elements.length; ++i) {
		data = parseInt(elements[i].getAttribute('data-count'),10);
		size = (fontDif * (data - lowVal) / sizeDif) + minFont;
		size = Math.round(size);
		elements[i].style.fontSize = size + "px";
	}
}

Now, an example on how to use the function once you include it one way or another in your HTML document.

<!doctype html>
<html>
	<head>
		<script src="tagcloud.js"></script>
	</head>
	<body>
		<div id="tagcloud" data-maxfont="32" data-minfont="12">
			<span data-count="18">lorem</span>
			<span data-count="5">ipsum</span>
			<span data-count="9">dolor</span>
			<span data-count="11">sit</span>
			<span data-count="14">amet</span>
			<span data-count="2">consectetur</span>
			<span data-count="16">adipiscing</span>
		</div>

		<script>
			var tc = document.getElementById('tagcloud');
			tagcloud(tc,'span');
		</script>

	</body>
</html>