Want to learn jQuery but you don’t know where to start from? Custom animations

jQuery

In the last lesson we took a quick look to the main default animations present in jQuery. But how to apply custom animations? Today, you gonna learn how to do it: let’s get started!

The “.animate()” function

Beyond other animation methods already seen before, jQuery provides the .animate() function which allows us to design our animations. This function takes an input of four parameters:

  • An array with the respective properties and values (similar to the one utilized for the css function) . Required
  • A string (slow,normal,fast) or the number of milliseconds representatives of the animation duration. Optional
  • A string which describes how to do the animation (easing type). Optional
  • A callback function, to be executed by the end of the animation. Optional

The syntax is as follows:

$("selected_element")
.animate( { property1:valore, property2:valore}, duration, easing, function_to_recall_by_end);

I will ignore the last two parameters for now, and will concentrate on the first two instead, taking into consideration they are more than enough to make the first animations.

How to use it?

The usage of the animate function is identical to that of the css function, the only difference being that in this case the item will pass from one value to another gradually, without a steep jump. As an example, let’s take this markup:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Animate!</title>
    <script src="jquery.js" type="text/javascript"></script>
    <script src="esempio.js" type="text/javascript"></script>
    <style type="text/css">
      #box{
        width:50px;
        height:50px;
        background-color:#00F;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
  </body>
</html>

We want to enlarge the size of the #box item. We can achieve this through the css function in this way:

$(document).ready(function() {
$("#box").css({height: "400px", width: "400px"});
});

As you can see, you cannot even notice that there is a transition from a div 50×50 ad uno 400×400. 50×50 to a 400×400 one. Let’s try now the animate function:

$(document).ready(function() {
$("#box").animate({height: "400px", width: "400px"},"slow");
});

It works better already! Through this function we can animate whatever CSS property that has a numerical value, thus margins, padding, edges, height, width, positions, opacity are all ideal candidates. The animation will have as a starting point the one specified in the stylesheet, and as a final point the one specified in the Javascript file.

In the previous animation we learned how to simultaneously animate two properties: in fact, our “box” increased likewise both in terms of height and width. We can animate a property (or groups of property) separately by linking together more calls to the animate function:

$(document).ready(function() {
$("#box")
.animate({height: "400px"},"slow")
.animate({width: "400px"},3000)
.animate({opacity: 0.2},1500);
});

Posso utilizzare solo valori numerici?

No. For the height, width e opacity properties other than numerical values, it is possible to specify text values as well::

  • show: gradually increases the properties, if it’s already the max, it does nothing.
  • hide: same thing as show, but it slowly decreases the value to zero. If it’s already zero, it does nothing.
  • toggle: alternates show and hide. If the property is visible, hides it, otherwise shows it.

Thanks to this last property, we can perform even more complex animations with fewer code lines, which keep track of the context. Let’s take as an example this markup:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
	"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Esempio - Continua a leggere...</title>
    <link rel="stylesheet" href="more.css" type="text/css" media="screen">
    <script src="../jquery.js" type="text/javascript"></script>
    <script src="more.js" type="text/javascript"></script>
  </head>
  <body>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tellus nisl, ullamcorper a interdum ullamcorper, suscipit at lacus. Nunc egestas varius leo, ac egestas augue bibendum non. Duis ligula purus, pulvinar eu porttitor fermentum, ultricies a ipsum.</p>
    <a id="more" href="#">Show/Hide</a>
    <p>This paragraph should be hidden when the page is loading. It should be shown only when the link right above is clicked.</p>
  </body>
</html>

We can hide and show the second paragraph easily through the animate function:

$(document).ready(function() {
$("p:eq(1)").hide();
$("a#more").click(function(){
$("p:eq(1)").animate({opacity:'toggle'},"slow");
return false;
});
});

Obtaining the following result. Be careful though: this is not an optimal solution, given that in case Javascript has been disabled, it won’t be possible to hide the paragraph.

When using the animate function, you need to be careful not to go against CSS rules. Let us take this simple labyrinth as an example. The HTML is a simple image and a div. The CSS associated with it is the following:

#omino {
background-color:#00F;
height:15px;
left:0px;
position:absolute;
top:250px;
width:15px;
}

The code that performs the animation is the following:

$(document).ready(function() {
$("#risolvi").click(function(){
$("#omino")
.css({top: 250,left:0})
.animate({left:'+=60px'},'slow')
.animate({top:'+=40px'},'slow')
.animate({left:'+=115px'},'slow')
.animate({top:'+=78px'},'slow')
.animate({left:'+=300px'},'slow');
});
});

As you can see, I have used the animate function to modify the top and leftproperties, but this would have not produced any movement, if I would have not positioned absolutely the div into the CSS. Therefore, it is important to carefully plan the animations..

Another thing that you can notice in the previous Javascript code, is the use of the operator +=. This operator allows the adding of a relative quantity: instead of moving the item to the “60px” position, moves it 60px from the current one.

Conclusions

We’ve covered a lot of ground until now. We got started with jQuery basic concepts, going through the managing of events, default animations, and today custom animations. These concepts should be enough for you to start creating your first functions by using this fantastic framework. In the following lectures you will see how this concepts are applied into “the real world”: in fact, I will show you some examples of jQuery codes functioning at 100%. Till next week then!

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: , ,

The Author

Fond of web design, takes delight in creating (X)HTML+CSS layouts. A maniac of polished and tidy codes, the type of person you find in your house straightening the paintings hanging on the wall. He has made his mind of becoming a web designer with a capital “w”, and spends entire nights awake in order to make his dream come true.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

2 comments

Trackback e pingback

  1. Wanna learn jQuery but you don’t know where to start from? Alternating functions, variables, first effects | Your Inspiration Web
    [...] Lesson 5: Custom animation Tags: javascript, jQuery The …
  2. You want to learn how to use jQuery but don’t know where to start? | Your Inspiration Web
    [...] Lesson 5: Custom animation Tags: Guides, javascript, jQuery [...]

Leave a Reply

Current month ye@r day *