Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

It's evolution, baby! Web animations from GIFs to CSS3

DZone's Guide to

It's evolution, baby! Web animations from GIFs to CSS3

· Web Dev Zone
Free Resource

Prove impact and reduce risk when rolling out new features. Optimizely Full Stack helps you experiment in any application.

From the beginning. 1987. The year when GIF was born

It was 1987 when the GIF format was introduced by the CompuServe company. After that, in 1989, animation support was added as one of the features. So, GIF became some kind of a standard in web animation. If somebody wanted to create an animated website back in the 90's, GIF was probably the first thing that they were thinking about. Here's an example of how it looked like back then. Seems like some things always remain the same, right?

This is not so hard to add some GIF animation to your page. For example, we want our link's background to change into an animated GIF image when we move the mouse cursor over it. We can use the :hover pseudo-class for that:

a:hover {
background-image: url(giphy.gif);
}

The background-image property is useful when you want to add some animation to your page background. Let's try to create a retro looking web page using this knowledge. You won't believe your eyes when you see how 90's it is! And we don't even need to work hard to do so. It's always retro when you use GIFs!

Here's the HTML code:

html
<!doctype html>
<html>
    <head>
        <title>Simple gif animation</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div id="container">
            <ul>
                <li><a href="">HOME</a></li>
                <li><a href="">PIZZA</a></li>
                <li><a href="">BURGERS</a></li>
                <li><a href="">DRINKS</a></li>
                <li><a href="">CALL US</a></li>
            </ul>
            <h2>Taste it all now! It will be too late tomorrow!!!</h2>
            <div id="ad">
            </div>
        </div>
    </body>
</html>

Done. This is all you need to create your own 90's style homemade Burger King website:


These burgers are animated. And the links, too:


There's not so much we can do with GIFs, to be honest. So, let's continue our time travel.

1995. New star rising. JavaScript appearance

JavaScript brought more interactivity into web applications. JavaScript frameworks are really handy, if you want to make some complex app faster. Some kind of a standard among them is jQuery. It contains a lot of useful functions which can help you manipulate the content almost any way you want. Some animation functions are available as well and we'll see how they work soon after. There are also a lot of animation frameworks out there. We'll use Animo.js as an example to see how they work.

.animate() it! jQuery animation capabilities


The main jQuery animation function is .animate(). It's easy to remember that name, isn't it? Syntax is rather easy too:

$(selector).animate( properties [, duration ] [, easing ] [, complete ] )

Here's a simple example of how it works. Imagine that we want to move the <div> element 200 pixels to the right and 200 pixels down after that:

html
<!doctype html>
<html>
<head>
    <script src="jquery-1.11.2.min.js"></script>
        <style>
            #box {
                width: 100px;
                height: 100px;
                border: 2px solid black;
                position: relative;
            }
        </style>
    </head>
    <body>
        <div id="box"></div>
        <script>
            $(document).ready(function() { 
              $('#box').animate({left: "200px"}, 600, function() {
                $('#box').animate({top: "200px"}, 600);
              });
            });
        </script>
    </body>
</html>

Just copy and paste it and you'll see. And remember to get the framework source code before trying.

Usually there's no need to use all the function's parameters. properties defines the CSS properties you want to change. duration sets the duration in milliseconds. We also used another .animate() function as a complete property. It will start working right after the main animate() function completes.

Let's examine it in practical example now. Here's the example of our site:


There is no need to add any content, because what we are interested in is that MENU button on the top left. And we want to animate it.

Here's  how it will look like after we push the MENU button:


What we can't show you is how our side-menu is sliding smoothly from the left. You will be able to test it by yourself after we complete our project. And one more thing before we started: notice how background changed after we pushed the MENU button. It moved to the right, just like the side-menu.

Let's start with the HTML code:

html
<!doctype html>
<html>
<head>
<title>jQuery animation</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="menu">
<a class="menu-close" href="#">CLOSE</a>
<div class="menu-first">
<ul>
<li><a href="#" class="sub-menu">MENU1<div class="pointer"></div></a></li>
<li><a href="#">MENU2<div class="pointer"></div></a></li>
<li><a href="#">MENU3<div class="pointer"></div></a></li>
<li><a href="#">MENU4<div class="pointer"></div></a></li>
<li><a href="#">MENU5<div class="pointer"></div></a></li>
</ul>
</div>
<div class="menu-second">
<ul>
<li><a href="#" class="back-button"><div class="pointer"></div>BACK</a></li>
<li><a href="#">SUBMENU1<div class="pointer"></div></a></li>
<li><a href="#">SUBMENU2<div class="pointer"></div></a></li>
<li><a href="#">SUBMENU3<div class="pointer"></div></a></li>
<li><a href="#">SUBMENU4<div class="pointer"></div></a></li>
</ul>
</div>
</div>
<div id="content"><a href="#" class="main-menu">MENU</a></div>
<script src="scripts/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>

Here's the deal. What we have here is the <div id="menu"></div> section which contains all the stuff we want our menu to contain. Link with the menu-close class will close our menu in case we can't take it anymore. First list within the <div class="menu-first"></div> is our basic menu. It appears after the MENU button is being pushed. All the menus inside of it are useless and we need them just as an example. All, but not the first one with the class-name sub-menu. It will open the second level menu with class-name menu-second. Second level menu is hidden by default. We'll show you how to hide it using CSS. What's interesting about the second level menu is the link with the back-button class. It will return us to the basic menu. We'll also add some effects for you to be entertained while main menu changes to sub-menu and vice versa. We also need the <div class="pointer"> element to point forward or backward.

Here's the CSS file:

html, body {
height: 100%;
}
body {
font-family: Helvetica, Arial, sans-serif;
left: 0;
  margin: 0;
  overflow: hidden;
  position: relative;
}
#content {
background-image: url('images/lil_back.jpg');
  background-repeat: cover;
  height: 100%;
}
#content a {
text-decoration: none;
color: white;
font-size: 1.3em;
position: relative;
top: 20px;
left: 20px;
}
#menu {
padding-top: 20px;
text-align: center;
width: 285px;
height: 100%;
position: fixed;
left: -285px;
background-color: #333;
}
#menu ul {
border-top: 1px solid #636366;
  list-style: none;
  margin-top: 20px;
  padding: 0;
}
#menu li {
border-bottom: 1px solid #636366;
padding-top: 7px;
padding-bottom: 10px;
margin-top: 10px;
}
#menu a {
text-decoration: none;
color: white;
}
.menu-close {
text-decoration: none;
color: white;
font-weight: bold;
}
.menu-second {
display: none;
}
.pointer {
width: 5px;
height: 5px;
border: 1px solid white;
margin-bottom: 2px;
margin-right: 5px;
margin-left: 5px;
border-radius: 100%;
color: white;
display: inline-block;
}

Notice how we hide the second level menu: we used the display: hidden property for that. By default, menu is placed 285 pixels to the left. What we need to do is move it 285 to the right with the animate() function. We also need to add the position: relative property to all the elements we want to move. Now, the animation!

First, prepare your app.js file:

js
var main = function() {

};

$(document).ready(main);

Now we will be adding the functions we need into the main function step by step. First of all, we need our menu to appear after we press the MENU button:

$('.main-menu').click(function() {
$('#menu').animate({left: "0px"}, 200);
$('body').animate({left: "285px"}, 200);
});

What happened here? We changed the left property for <div id=menu></div> element. It changes it's position from the original left: -285px to the left: 0px and it will take 200 milliseconds to do it. All the content inside the <body></body> tags will also move. Why? Because it's prettier that way, that's why.

The menu-close button will hide the menu. We talked about it earlier. The code is pretty much the same, but now we want our menu to disappear:

$('.menu-close').click(function() {
$('#menu').animate({left: "-285px"}, 200);
$('body').animate({left: "0px"}, 200);
});

We can now open and hide our menu-box. And this is the time to add some effects to the menu itself. Let's make it fading in and fading out when we are opening and closing the sub-menu:

$('.sub-menu').click(function() {
$('.menu-first').fadeOut(200, function() {
$('.menu-second').fadeIn(200);
});
});

We used the so-called callback function here. It will start to work right after the .fadeOut() functions ends. The Back button is working the same way, but reversed:

$('.back-button').click(function() {
$('.menu-second').fadeOut(200, function() {
$('.menu-first').fadeIn(200);
});
});

That's all we need to turn our boring menu-box into the animated one.

These are not all the effects functions jQuery allows you to use. There are also show(), hide(), slideUp(), slideDown(), slideToggle(), and some others. You cah check the Effects page to see them all.

We will now continue with the framework that specializes on the animation effects above all.

Animation frameworks. Animo.js

Animo.js logo

Animo.js is basically a set of animation functions. It's better for you to check the home page. Pretty demos are waiting for you there. We'll use some of the available effects to create a good-looking presentation page. It will contain some images with different animation effects.

The HTML code:

html
<!doctype html>
<html>
<head>
    <title>Animo.js</title>
    <link rel="stylesheet" type="text/css" href="style.css">  
    <link href="animate-animo.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="scripts/jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="scripts/animo.js"></script>
    <script type="text/javascript" src="scripts/app.js"></script>
    </head>
    <body>
    <div id="content">
    <h1>Travel like a boss!</h1>
    <p>Blah-blah-blah</p>
    <img id="image-one" src='images/paris_1.jpg'>
    <p>Blah-blah-blah</p>
    <div class="two-images">
    <img id="image-two" src="images/paris_2.jpg">
    <img id="image-three" src="images/paris_3.jpg">
    </div>
    <p>Blah-blah-blah</p>
    <img id="image-four" src="images/paris_4.jpg">
    <p>Blah-blah-blah</p>
    <img id="image-five" src="images/paris_5.jpg">
    <p>Blah-blah-blah</p>
    </div>
    </body>
</html>

Check all the <link> and <script> tags first. Animo's dependency is jQuery version 2 or later. You also need to include the animo's stylesheet which available from the project's github page.

I've deleted all the paragraph text because this is not why we are here. We'll get the access to our images through the id parameter, so don't forget to set it right.

Now, check the CSS positioning:

body, #content {
height: 100%;
}
body {
    font-family: Helvetica, Arial, sans-serif;
    margin: 0px;
    padding: 0px;
    background-image: url(images/lil_cover.jpg);
    background-attachment: fixed;
}
#content {
width: 660px;
background-color: #60a0aa;
margin-top: 0px;
padding-top: 10px;
margin-left: auto;
margin-right: auto;
text-align: center;
color: white;
height: 100%;
}
#content p {
text-align: justify;
margin-left: 20px;
margin-right: 20px;
}

#image-one {
float: left;
position: relative;
left: -70px;
margin-bottom: 10px;
}
.two-images {
height: 500px;
}
#image-two {

position: relative;
left: -170px;
display: none;
}
#image-three {
position: relative;
top: -190px;
left: 110px;
display: none;
}
#image-four {
float: right;
position: relative;
left: 60px;
margin-bottom: 10px;
}
#image-five {
float: left;
position: relative;
left: -30px;
margin-bottom: 10px;
}

To make it look more fashionable we moved our images from their original positions to the right or to the left using the position: relative property to make them free and the left: 60px property, for example, to move them to the right. Notice the <div class="two-images"> section. It's empty by default. We made our image-two and image-three invisible. They will appear inside this <div> when we want to:

Before:


After:


We'll use the .scrollTop() function to determine when the animation should start. This is rather primitive way to create a scroll-based animation. Better check some particular frameworks, which were created to handle the scrolling process.

First of all, we need to prepare the basic functions:

$(document).ready(function() {

});
$(document).scroll(function() {

});

We'll use the ready() function to prepare our images right after the document loading completes. The scroll() function will handle the scrolling process. It will determine when animation should start. The .scrollTop() function will help us. It returns the number of pixels that are hidden from view above the scrollable area. If you want to create a web site with responsive design, you should pay some respect to the page's width.

Let's now add the tada effect to the first image. Add this code to your scroll() function:

if ($(window).scrollTop() > 300 && $(window).scrollTop() < 340) {
$('#image-one').animo( { animation: 'tada' } );  
}

It tells that we should start the animation somewhere between 300 and 340 pixels from above. It's the time when the first-image will be placed in the middle of the page.

The second part is a little bit more difficult:

if ($(window).scrollTop() > 1000 && $(window).scrollTop() < 1050) {
$('#image-two').css('display', 'block');
    $('#image-two').animo({animation: "fadeInLeft", duration: 0.5});  
    $('#image-three').css('display', 'block');
    $('#image-three').animo({animation: "fadeInRight", duration: 0.5});  
}

First, we need to change the display property to the block value to make our images visible. Then we run two types of animation: fadeInLeft and fadeInRigth to make them appear from nowhere. Some kind of a surprise for possible visitors!

Next animation effect is rotation. And now we'll prepare our images right after the whole document is loaded:

$(document).ready(function() {
$('#image-four').animo('rotate', {degrees: 90});
$('#image-five').animo('rotate', {degrees: -90});
});

We rotated them  90 degrees from their original position. Now, when you scroll the page long enough to see them, they will slowly rotate to their original location:

if ($(window).scrollTop() > 1900 && $(window).scrollTop() < 1950) {
$('#image-four').animo('rotate', {degrees: 0, duration: 0.6});
}
if ($(window).scrollTop() > 2370) {
$('#image-five').animo('rotate', {degrees: 0, duration: 0.6});
}

This is how you can use this framework. You just need to connect the proper effect with the certain handler and everything will work fine.

Present days. HTML5 and CSS3. Something that everybody's talking about

If you're interested in web development, you probably heard about these two. Besides the style creation and objects alignment, CSS3 also allows you to create animated objects.

When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current style to the new one.

First of all, the basics:

@keyframes animate {
    from {left: 0px;}
    to {left: 200px;}
}

div {
    width: 100px;
    height: 100px;
    border: 2px solid black; 
    animation-name: animate;
    animation-duration: 1s;
}
```
For webkit-based browsers, such as Chrome, Safari, and Opera, you should use: 
```
@-webkit-keyframes animate {

}
div {
-webkit-animation-name: animate;
-webkit-animation-duration: 1s;
}

It works pretty much the same as the .animate() function in jQuery works. We define the animation behavior with @keyframes and then use the animation-name and animaion-duration properties to apply our animation to the <div> we want to animate.

You can run your animation step-by-step using percentage. It works like this:

@keyframes animate {
0% {left: 0px; top: 0px;}
50% {left: 200px; top: 0px;}
100% {left: 200px; top: 200px;}
}

#box {
width: 100px;
height: 100px;
border: 2px solid black;
position: relative;
animation-name: animate;
animation-duration: 1.2s;
}

As you can see, this code repeats the simple .animate() example we made to move our <div> with jQuery.

You can also set a delay for animation to start with the animation-delay and -webkit-animation-delay properties.  The animation-iteration-count and -webkit-animation-iteration-count properties  set the number of times an animation should repeat. You can use an integer or an infinite value to run your animations infinitely until, I don't know, the sun collapses. You can use  animation-direction and -webkit-animation-direction in case you want to run your animation in reverse, for example. Use the reverse value for that purpose. With the alternate value set up, animation will run forward, then backward, then forward. Then? Backward again, that's right. The last properties we want to tell you about are the animation-timing-function and -webkit-animation-timing-function properties. Possible values are:

- ease - animation runs slowly, then fast, then ends slowly (this is the default one)

- linear - animation speed is the same from the start to the end

- ease-in - animation with the slow start

- ease-out - animation with the slow end

- ease-in-out - animation with the slow start and end

- cubic-bezier(n,n,n,n) - with this one you can define your own values in a cubic-bezier function

You can use the short form for all that properties:

div {
    animation: animate 1.2s linear 2s infinite alternate;
}

Notice that the first time value corresponds to the animation-duration and the second one - to the animation-delay.

And now it's time to make something useful with all those properties. We'll create the fade-in effect with css only. It will run fade-in animation effect similar to the one we've used with Animo.js.

Here's the code:

html
<!doctype html>
<html>
<head>
<title>Fade In Animation With CSS3</title>
</head>
<body>
<style type="text/css">
@keyframes fadeIn {
from {opacity: 0; left: 0px;}
to {opacity: 1; left: 40px;}
}
@-webkit-keyframes fadeIn { 
from { opacity:0; left: 0px;} 
to { opacity:1; left: 40px;} 
}

div {
position: relative;
opacity: 0; /*make div invisible upon start */
animation: fadeIn 0.5s linear 1;
-webkit-animation: fadeIn 0.5s linear 1;

animation-fill-mode:forwards;
-webkit-animation-fill-mode:forwards; 
}
</style>

<div>
<img src="paris_2.jpg">
</div>
</body>
</html>

All the properties are familiar to us, so there's nothing to be afraid of. Except for the animation-fill-mode property maybe. This is something new. We need it to be sure that we will remain at the last keyframe after animation is done. In this case, the last keyframe is a combination of two properties: opacity: 1 and left: 40px. Without this last property the <div></div> element will disappear again.

It works. But you should always keep in mind how to make your code work well in different browsers.

Enjoy your CSS

Creation of css animations can be a boring and lengthy process of adding necessary css styles and vendor prefixes (especially for different browsers). This problem can be partly settled thanks to the use of css generators. You've probably used some of them when you needed to create a cross-browser gradient or a box shadow. Some css generators can do not only this but also animations, like, for example, EnjoyCSS develped by a small software development company.

Here's a gallery of available templates.


Let's take a look at Transition.


It contains an example of hover controlled animation. There are interactive "Before" and "After" views. You can use this menu on the right to set proper CSS values.

All you need to do after the values are defined is to choose the target browsers and EnjoyCSS will do all the work for you:


You can also check the web developer's page for the key EnjoyCSS features.

Enjoy it!

Conclusion

What's good about the CSS3 animation? First of all, it looks more natural comparing to frameworks. You don't ever need to download any source codes you need to use in case of frameworks. If you create a web page, you probably will work with styles. So, why not create some animations at the same time? They are hardware accelerated, which is not so important when you use them on your desktop. But it WILL BE if you decide to use your mobile browser. But, here's the bad side: you can't start your animations one after another since there is no callback functionality available with CSS3. Animations start right after the page loading completes or you can use the hover pseudo-class to trigger them. If you want to use event-oriented animation, you should use JavaScript or JavaScript frameworks. You can choose between big frameworks, which contain animation functions among the others, and animation-oriented frameworks such as Animo.js. By the way, CSS3 frameworks are available too. For example, Animate.css, which is used inside of Animo.js. CSS3 code generators will help you to finish your code faster. You are also free to use the GIF animation, if you want to. We won't judge you.

Well, that's enough for today. Hope, you liked it. See ya!

With SDKs for all major client and server side platforms, you can experiment on any platform with Optimizely Full Stack.

Topics:
css ,html5 ,javascript ,jquery ,css animation

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}