jQuery: animations without animate()

In this post I'm going to show you how to create jQuery animations without using the animate() method, but only with CSS rules and a couple of JavaScript timers. The final effect we want to achieve is that of a box that decreases in size, disappears and then it's replaced by another box that increases its size until it reaches the dimensions of the previous box while also changing its background color. Here's how we can do with jQuery and JavaScript timers:

$(document).ready(function() {

  var initialCSS = {
    background: '#d40',
    width: '200px',
    height: '200px'
  };
  
  var finalCSS = {
    background: 'orange',
    width: '100px',
    height: '100px'
  };
  
  var width = 200;
  var height = 200;
  
  $('#test').css(initialCSS);
  
  var interval = window.setInterval(function() {
  
    width -= 1;
    height -= 1;
  
  
    $('#test').css({
      width: width,
      height: height
    });
    
    if(width == 0 && height == 0) {
    
     
      $('#test').css(finalCSS);
      
      window.clearInterval(interval);
      
     
      
      width = 100;
      height = 100;
      
      var interval2 = window.setInterval(function() {
      
        width += 1;
        height += 1;
        
        $('#test').css({
          width: width,
          height: height
        });
        
        if(width == 200 && height == 200) {
        
        
          window.clearInterval(interval2);
        
        }
      
      
      
      }, 50);
      
    }
  
  
  
  
 }, 50 );
  

});

First, we use two object literals to store the CSS values to be applied to our element through the css() method. Then we initialize two counters: one with the initial dimensions of the element and the other one with its final dimensions. The former is put within a timer that decreases the counter's value until it reaches 0. The latter, instead, is contained within a second timer that starts when the first stops and it increases the counter's value until it reaches 200. Then also this timer is reset. You can see the 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.