Your friends at Viget present Inspire, a Design & Interaction Blog

Fun With jQuery’s Animate() Function

I'm a huge jQuery fan; there's no hiding that. For me, a designer, there is no easier JavaScript library to use and learn. I've been leaning on jQuery to do my heavy lifting for a while now, and it continues to blow me away almost every time. With each passing release, the library just gets better.

In jQuery's 1.2 release, we saw a big update to animate() function. Previous to 1.2, you could only animate absolutely positioned elements, but now the function supports most anything you could need. This includes padding, margin, font-size, relatively positioned elements, width, height, and borders. Since 1.2, I've been tinkering with numerous different examples. Below are three of my most recent. I hope you find them informative and/or helpful.

+ See Code

var navDuration = 150; //time in miliseconds
      var navJumpHeight = "0.45em";

      $('#nav1 li').hover(function() {
          $(this).animate({ top : "-="+navJumpHeight }, navDuration);            
      }, function() {
          $(this).animate({ top : "15px" }, navDuration);
      });

(Click a link!)

+ See Code

$('#nav_move').css({ 
        width: $('#nav2 li:first a').width()+20, 
        height: $('#nav2 li:first a').height()+20 
      });
      $('#nav2 li:first a').addClass('cur');
      
      $('#nav2 a').click(function() {
        var offset = $(this).offset();
        var offsetBody = $('#content').offset(); //find the offset of the wrapping div    
        $('#nav_move').animate(
          { 
            width: $(this).width()+20, 
            height: $(this).height()+20, 
            left: (offset.left - offsetBody.left) 
          }, 
          { duration: 350, easing: 'easeInOutCirc' }
        );
        $('.cur').removeClass('cur');
        $(this).addClass('cur');
        return false;
      });

+ See Code

var fadeDuration = 150; //time in milliseconds
      
      $('#list1 li a').hover(function() {
        $(this).animate({ paddingLeft: '30px' }, fadeDuration);
        $(this).children('span').show().animate({ left: -5 }, fadeDuration);
      }, function() {
        $(this).animate({ paddingLeft: '15px' }, fadeDuration);
        $(this).children('span').animate({ left: -35 }, fadeDuration).fadeOut(fadeDuration);          
      });

For any further reading on jQuery, check out: