jQuery: a tag cloud with CSS classes

We want a tag cloud with different CSS classes applied to links. To start with, here is a basic structure for our tag cloud:

<ul id="tag-cloud">
<li><a href="#">CSS</a></li>
<li><a href="#">DOM</a></li>
<li><a href="#">ECMAScript</a></li>
<li><a href="#">HTML5</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">PHP</a></li>
<li><a href="#">Python</a></li>
<li><a href="#">SVG</a></li>
<li><a href="#">XML</a></li>
<li><a href="#">XSLT</a></li>
</ul>

We're using an unordered list to preserve the fundamental semantics of our tag cloud. Now we can add our CSS styles:

body {

    width: 50%;
    margin: 0 auto;
    font: 62.5%/1 Arial, sans-serif;
    background: #fff;
    color: #333;
    padding: 2em 0;

}

a:link, a:visited {

    color: #338;
    text-decoration: none;

}

#tag-cloud {

    height: 100%;
    width: 60%;
    margin: 0 auto;
    padding: 0;
    list-style: none;
    font-size: 1.3em;

}

#tag-cloud li {

    display: inline;
    padding-right: 0.3em;

}

/* jQuery classes */

a.css {font-size: 2em; color: #c60;}
a.dom {font-size: 1.4em; color: #c00;}
a.ecmascript {font-size: 1.1em; color: #555;}
a.html5 {font-size: 1.8em; color: #0df;}
a.javascript{font-size: 1.9em; color: #393;}
a.php {font-size: 1.8em; color: #933;}
a.python {font-size: 1.3em; color: #00f;}
a.svg {font-size: 1em; font-weight: bold; color:fuchsia;}
a.xml {font-size: 1.9em; color: purple;}
a.xslt {font-size: 1.6em; color: green;}

Finally, let's add jQuery:

$(document).ready(function() {

    $('#tag-cloud li').each(function() {
    
        
        var $a = $(this).find('a');
        var text = $a.text();
        
        
        
        switch(text) {
        
            case 'CSS':
            $a.addClass('css');
            break;
            case 'DOM':
            $a.addClass('dom');
            break;
            case'ECMAScript':
            $a.addClass('ecmascript');
            break;
            case 'HTML5':
            $a.addClass('html5');
            break;
            case 'JavaScript':
            $a.addClass('javascript');
            break;
            case 'PHP':
            $a.addClass('php');
            break;
            case 'Python':
            $a.addClass('python');
            break;
            case 'SVG':
            $a.addClass('svg');
            break;
            case 'XML':
            $a.addClass('xml');
            break;
            case 'XSLT':
            $a.addClass('xslt');
            break;
            
            default:
            break;
        
        }
    
   });
    

});

That's simple: we iterate over each list item and find the text contained within each link. Then we use the switch construct in order to apply the appropriate CSS class depending on the text node of the links. You can see the result below.

Screenshot

Leave a Reply

Note: Only a member of this blog may post a comment.