6/10/12

Creating Intricate Animation Effects Using JavaScript / JQuery

This tutorial will provide you with professional flip and rotation effects that can appear to spin an object around to reveal the opposite side or rotate the image. Three different spin effects will be provided as well as a few rotation effects, making this a great way to increase the aesthetic value of your web pages. This method takes two objects and then animates them so that they appear to flip over as if they are attached back to back. It requires these arguments:

               
id1 : An object or object ID -it may not be an array                            
id2 : An object or object ID - it may not be an array
w : If true or 1, the width will be flipped
: If true or 1, the height will be flipped
msecs : The number of milliseconds the flip should take                
pad : If set, the objects will be padded to retain their overall dimensions during the flip                        


Variables, Arrays, and Functions


swap
Local string variable containing a command string suitable for InsVars() to add a call to VisibilityToggle() to a chain
fast
Local string variable containing a command string suitable for InsVars() to add a 1 millisecond call to ZoomToggle() to a chain
slow
Local string variable containing a command string suitable for InsVars() to add a call of length msecs / 2 to ZoomToggle() to a chain
ZO_Flag
Property of either or both id1 and id2, which is set if a zooms already in operation on an object
CallBack()
Plug-in to enable any command to be added to a chain
VisibilityToggle()
Plug-in to toggle the visibility of an object
ZoomToggle()
Plug-in to toggle the zoom state of an object
Chain()
Plug-in to start a chain of calls executing



This function starts by checking the state of both id1 and id2’s ZO_Flag property. If either is true, a zoom is already in operation on an object, so the function returns, like this:


if (O(id1).ZO_Flag || O(id2).ZO_Flag) return


Next, three local string variables are created as a way to keep the code tidy and stop any lines wrapping around. They are also efficient as each string is used twice. These are the assignments:

var swap = "ChainThis('VisibilityToggle(\"#1\")')"
var fast = "ZoomToggle('#1', #2, #3, 1, #4, 0)"

var slow = "ZoomToggle('#1', #2, #3, #4, #5, 0)"



The variable swap is assigned a string suitable for enabling the VisibilityToggle() plug-in to be used in a chain (by implementing it via a ChainThis() plug-in). The strings fast and slow contain strings to place calls to the ZoomToggle() plug-in, one of them taking 1 millisecond (and therefore being virtually instantaneous) and the other taking a specified time.

The #1, #2, and so on within the strings are variable or value place holders. When these strings are passed to an InsVars() plug-in, these place holders will be replaced by the values or variables also passed to it.


The final call in the plug-in is to the Chain() plug-in, passing it a sequence of six commands, which are all passed through the InsVars() plug-in to combine the strings with the variables, like this:


Chain(Array(
      InsVars(slow, id1, w, h, msecs / 2, pad),
      InsVars(fast, id2, w, h, pad),
      InsVars(swap, id2 ),
      InsVars(slow, id2, w, h, msecs / 2, pad),
      InsVars(swap, id1 ),
      InsVars(fast, id1, w, h, pad)

))



The code is spaced into columns in order to allow you to see the values being passed more clearly. The sequence of commands performs the following six steps:


1. Zoom id1 down over half the time specified in msecs: This performs the first half of the flip animation.

2. Zoom id2 down over the course of 1 millisecond: This ensures that id2 is quickly zoomed down so that can be zoomed up shortly at normal speed.

3. Toggle id2’s visibility (from hidden to visible): After id2 has been zoomed down, this makes it safe to make it visible ready for zooming up.
4. Zoom id2 up over half the time specified in msecs: This performs the second half of the flip animation.
5. Toggle id1’s visibility (from visible to hidden): This tidies up after the flip by making id1 invisible.
6. Zoom id1 up over the course of 1 millisecond: Once invisible, id1 is zoomed back up again, and the objects are then in a state where the flip can be reversed.

                

To create a flip animation, you need to first have two objects of equal dimensions. They must then be overlaid on each other with the second object’s visibility property turned off, using code such as this:


ids = Array('a', 'b')
Locate(ids, ABS, 10, 10)
VisibilityToggle('b')

Flip('a', 'b', 1, 0, 1000, 0)


This code takes two objects that have been given the IDs of ‘a’ and ‘b’, places their names in the array ids, and then locates them at the absolute position 10,10 with a call to the Locate() plug-in. Object ‘b’ then has its visibility turned off by the VisibilityToggle() plug-in. Finally, the Flip() plug-in is called with the two objects and set to flip only the width (so that the flip will twist around the vertical axis). A time of 1000 milliseconds is specified and padding is not used.
               
Here’s an example that creates a mini web page on the subject of general relativity with a photo of Albert Einstein that flips when you pass the mouse over it, revealing more information on the reverse side:



                                                          Front  



Back 





<img id='a' src='einstein1.png' />
<img id='b' src='einstein2.png' />
<div id='c'><font size='5'><b>General Relativity</b></font>
<p align='justify'>General relativity is a theory of gravitation developed by Einstein in the years 1907–1915. The development of general relativity began with the equivalence principle, under which the states of accelerated motion and being at rest in a gravitational field (for example when standing on the surface of the Earth) are physically identical. The upshot of this is that free fall is inertial motion; an object in free fall is falling because that is how objects move when there is no force being exerted on them, instead of this
being due to the force of gravity as is the case in classical mechanics.</p></div>
<script>
window.onload = function()
{
Hide('c')

width = GetWindowWidth() 

                Resize('c', width - 220, 260)
                Show('c')
                ids = Array('a', 'b')
                Locate(ids, ABS, width - 205, 5)
                Resize(ids, 200, 264)
                VisibilityToggle('b') 
                O('a').onmouseover = function() { Flip('a', 'b', 1, 0, 250, 0) }
                O('b').onmouseout = function() { Flip('b', 'a', 1, 0, 250, 0) }
}

</script> 



The HTML section displays the two images along with a div containing the article text.


The <script> section then hides the text with a call to Hide() because it is going to be resized; if it didn’t do this, the Internet Explorer browser would return the wrong browser width in the next command as it would prepare for possibly requiring a scroll bar. After resizing the article text, the Show() plug-in is called to display it again and, now that it has its dimensions reduced to fit within the current window, Internet Explorer will not try to leave a gap for a scroll bar in case it should need it.

Next, the ids array is populated with the image IDs and is passed to the Locate() plug-in to place them at the top right corner of the browser. The Resize() plug-in is also called because, unfortunately, odd widths and heights sometimes cause a slight 1-pixel disturbance to animations depending on the browser used (something to do with the way they handle rounding), so ensuring that both dimensions of objects passed to Flip() are even is the easiest way to get the best results. It also ensures that both images have the same dimensions and will flip neatly.

Next, the second object is set to invisible before setting up the mouse events to call Flip(). This must be done because the two images are overlaid on each other and could have varying zIndex values, so you must ensure the correct one is at the front by making the other one invisible.

In the final two lines, the onmouseover event of object ‘a’ is attached to a flip from object ‘a’ to ‘b’, while the onmouseout event of object ‘b’ is attached to a flip from object ‘b’ to ‘a’.

Before any flips, object ‘a’ will be visible, so passing the mouse over it will start the flip.

After the flip has finished, object ‘b’ will be visible and the mouse will still be over it (unless the user quickly moved it away), which is why the onmouseout even of object ‘b’ is attached so the animation will flip back again when the mouse moves away.



Although images give the best flip results, you can pass any kind of object such as a div or table and so on, to the Flip() plug-in. This means you could, for example, have an e-mail button that flips over when the mouse passes over it to reveal a small form for entering your e-mail address to subscribe to newsletters. If you do this, text and objects will flow in and out of the object rather than rotate the way an image does, so you get a slightly different—but still interesting—effect.

You can also use Flip() to swap sections of HTML according to the selection of radio button or clicking of links. And don’t forget that you can flip objects horizontally and vertically, or you can even do both at the same time to create a zoom-away-and-back-again effect. Try changing the values in the Flip() calls of the last two lines of the example andsee what different results you get.



This method allows objects/images to be rotated immediately or during animation. To Rotate an object requires the following arguments:


angle:  angle value in degrees          
animateTo: angle value in degrees to be animated to 
duration: The duration of the animation specified       
bind:  binds events to objects



Variables, Arrays, and Functions
rotate()
Plug-in enabled to rotate objects/images by any given angle (default value = 0)
step
Executed on every animation step
easing
Executed to create fluid animation
Callback()
Plug-in to enable any command to be added to a chain
getRotateAngle
Returns current angle of rotated object
stopRotate
Stops animation period

The Plug-in (Rotate)



 An explanation of how this code works is rather difficult to explain in one article as sometimes the string must be modified according to browser usage. Though it is worthy to note that the plug-in provided allows for simple compact modification of HTML code in order to allow objects to rotate using various events such as Onmouseover and Onmouseout.



In order to use the plug-in simply incorporate the script following your main jquery. For example:



 $("#image").rotate({

        bind: {

            click: function(){
                      $("#image").rotate({
                          angle: 0,
                          animateTo: 180,
                          duration: 6000
                      });
                      setTimeout(function(){
                          $("#image").stopRotate();
                      }, 1000);
            }
       }
   });

                When the onclick event is triggered the image would animate rotating Like so:




The plugin could also be used to keep the image rotating constantly. By simply modifying the script to this:



var angle = 0;
setInterval(function(){
      angle+=3;
     $("#img").rotate(angle);

},50);



                Here is an example of the code used alongside the Onmouseover event:



$("#img").rotate({
   bind:
     {
        mouseover : function() {
            $(this).rotate({animateTo:180})
        },
        mouseout : function() {
            $(this).rotate({animateTo:0})
        }
     }
  

});



Upon removing your mouse from the image/obect, the Onmouseout event would trigger. Thus returning the image to its original position. All the examples listed are working codes that can be used to modify the plug-in, simply incorporate them into your code and modify according to preference.


The Plug-In (FLIP)



function Flip(id1, id2, w, h, msecs, pad)
{
            if (O(id1).ZO_Flag || O(id2).ZO_Flag) return
            var swap = "ChainThis('VisibilityToggle(\"#1\")')"
            var fast = "ZoomToggle('#1', #2, #3, 1, #4, 0)"

            var slow = "ZoomToggle('#1', #2, #3, #4, #5, 0)"


            Chain(Array(
                 InsVars(slow, id1, w, h, msecs / 2, pad),
                 InsVars(fast, id2, w, h, pad),
                 InsVars(swap, id2 ),
                 InsVars(slow, id2, w, h, msecs / 2, pad),
                 InsVars(swap, id1 ),
                 InsVars(fast, id1, w, h, pad)
        ))
}

Click on the link to download the demo files and see how this actually works. CLICK HERE


Article by Bill Kilpatrick
Bill is the marketing manager at Spotted Frog Design, a web development and online marketing
company based in the Philadelphia area. For more information, please visit their blog.
If you like This post, you can follow Code 2 Learn on Twitter.
Subscribe to Code 2 Learn feed via RSS or EMAIL to receive instant updates.
Want to write for Code 2 Learn. Email us. info

SHARE THIS POST:

0 comments:

Post a Comment