jQuery: animating a tag cloud

jQuery can virtually animate any kind of HTML elements or structures, so why don't we use it to animate a tag cloud? The effect we want to achieve is a zoom animation with a smooth bounce on hover. For that reason, we'll also use jQuery UI. Let's see how.

We start with the following markup:

<ul id="tag-cloud">
    <li class="tc-1"><a href="#">CSS</a></li>
    <li class="tc-2"><a href="#">HTML5</a></li>
    <li class="tc-2"><a href="#">JavaScript</a></li>
    <li class="tc-3"><a href="#">jQuery</a></li>
    <li class="tc-4"><a href="#">PHP</a></li>
    <li class="tc-5"><a href="#">Wordpress</a></li>
</ul>​

Then we add the following styles:

body {
    margin: 2em;
    padding: 0;
    font: 100% Arial, sans-serif;
}

#tag-cloud {
    width: 18em;
    margin: 0;
    padding: 1em;
    line-height: 1.4;
    background: #f5f5f5;
    border-radius: 12px;
    box-shadow: 3px 3px 3px #ccc;
}

#tag-cloud li {
    margin: 0 0.5em;
    display: inline;
}

#tag-cloud li a {
    color: #d34545;
    text-decoration: none;
    font-weight: bold;
}

#tag-cloud li a:hover {
    color: #fff;
    background: #d34545;
    padding: 3px 5px;
    border-radius: 6px;
}

#tag-cloud li.tc-2 a {
    font-size: 1.2em;
}

#tag-cloud li.tc-3 a {
    font-size: 1.4em;
}

#tag-cloud li.tc-4 a {
    font-size: 1.6em;
}

#tag-cloud li.tc-5 a {
    font-size: 1.8em;
}​

With jQuery, we'll use the base font size of each item to create our animation:

$(function() {

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

    var $li = $(this);
    var $a = $('a', $li);
    var fontSize = parseInt($a.css('fontSize'));

    $a.hover(function() {
    
      $a.stop(true, true).animate({
        fontSize: fontSize + 4 + 'px'
      }, 'slow', 'easeOutBounce');
    
    
    }, function() {
    
      $a.stop(true, true).animate({
        fontSize: fontSize + 'px'
      }, 'slow', 'easeOutBounce');
    
    
    });    
  
  });
  
});​

You can see the demo below.

Demo

Live demo

Back to top