jQuery: fold effect

Scriptaculous has another nice visual effect called Fold(). This effect adjusts the width and height of an element until it completely disappears. Emulating this effect with jQuery is a little more complicated than one could expect. The jQuery's animate() method can accomplish this task by setting the dimensions of an element to zero, but this effect is different from the original one that we want to reproduce. We need a jQuery's plugin that makes use of timers and accepts as its sole parameter a factor to progressively reduce an element's dimensions. Here's the code:

(function($) {

  $.fn.fold = function(factor) {
  
    factor = factor || 1;
  
    var cWidth = this.width();
    var cHeight = this.height();
    
    
    return this.each(function() {
    
      var element = $(this);
    
      var interval = window.setInterval(function() {
      
        cWidth -= factor;
        cHeight -= factor;
        
        element.css({height: cHeight, width: cWidth});
        
        if(cWidth == 0 && cHeight == 0) {
        
        
          window.clearInterval(interval);
        
        
        }
        
      }, 25);
      
    });
  };
})(jQuery);

The greater the factor used, the faster the animation. A simple test:

$('#run').click(function(e) {
  
    $('#test').fold();
  
  
    e.preventDefault();
  
  
});

You can see a demo below.

Demo

Live demo

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

Leave a Reply

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