JavaScript animations without jQuery

My readers know very well that I'm a big fan of jQuery, but the problem with jQuery is that it's an addictive framework that sometimes makes our life a little bit too easy. So I decided to try the hard way: implementing an animation without jQuery. In jQuery, you simply use the animate() method and you're done. In this case, we're going to create an animation from scratch. First, we need a simple element to work with, so I've set up an empty element with the following CSS rules:

#test {
  width: 0px;
  height: 0px;
  background: orange;
  overflow: hidden;
}

We want this element to expand its dimensions until it reaches 150 pixels in width and in height, so that it reveals itself. Finally, we also want that this element disappear when the first animation is complete. To accomplish this task, we need a counter to be incremented and two nested timers created using the setInterval() global function. But first we have to create our custom object:

function Animator(element) {

    var that = this;

    this.element = document.getElementById(element) || null;

    // more code here

}

This object accepts a reference to a target element as its sole parameter. Now let's implement the animate() method:

this.animate = function() {

        var counter = 0;    

        var interval = window.setInterval(function() {

            counter += 10;

            that.element.style.width = counter + 'px';
            that.element.style.height = counter + 'px';

            if(counter == 150) {

                clearInterval(interval);

                var interval2 = window.setInterval(function() {

                    counter -= 10;

                    that.element.style.width = counter + 'px';
                    that.element.style.height = counter + 'px';

                    if(counter == 0) {

                        clearInterval(interval2);

                    }

                }, 50);

            }

        }, 50);

};

The first counter goes up to 150, then the first timer is reset and the second animation starts. The second timer is decreased each time by 10 and when it reaches 0, also the this timer is reset. You can see a demo below.

Demo

Live demo

Comments are closed.