Create Animations & Effects using jQuery

Background: 

We so far have seen different ways to manipulate the DOM. While manipulating DOM elements we can add some basic effects to make the UI more attractive. There are built-in methods that jQuery provides to achieve different effects and simply calling those methods against different selectors we can easily create the animations. Using jQuery we can fade/slide an element using in-built methods. There are ways to create custom animations and add a callback function and to stop the animation whenever required. Let's look briefly about how we can create basic effects using these methods.

Hide,Show & Toggle methods:

One of the most basic effect we can have using jQuery is to hide/show certain element. In order to hide/show DOM element jQuery provides two method hide() and show().


So to hide/show a particular div we will use :
$("#div1").hide();//hides the element with id "div1"
$("#div1").show();//shows the element with id "div1"

these 2 methods will hide or show the element irrespective of the current visual state of the element, i.e with show() method applied to an already visible element will not visibly change anything.

There are 2 optional parameters to these methods:

  1. Speed: Specify the speed of hiding/showing
  2. Callback : Any custom callback jQuery method that will execute after.
As speed parameter we can pass either "slow", "fast" or any millisecond value.

Apart from these two methods, there is another method toggle(). This will toggle the visible state of the element. i.e. when applied this method will hide an already visible element and show a hidden element.

The syntax for these 3 methods are similar:

$(selector).hide(speed,callback);
$(selector).show(speed,callback);
$(selector).toggle(speed,callback);


Refer the Following Example which uses these methods using a "slow" speed.

<head>   
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="divContent">Content Div</div>
    <br/>  
    <button id="btn1">Hide</button>
    <button id="btn2">Show</button>
    <button id="btn3">Toggle</button>
    <script>
        $( "#btn1" ).click(function(){
            $("#divContent").hide("slow",function(){
                alert("Hide Clicked");
            });
        });
        $( "#btn2" ).click(function(){
            $("#divContent").show("slow",function(){
                alert("Show Clicked");
            });
        });
        $( "#btn3" ).click(function(){
            $("#divContent").toggle("slow",function(){
                alert("Toggle Clicked");
            });
        });
    </script>
    </body>
</html>

Fading/Sliding of elements:

Fading:

Like hide/show and toggle we can use the fade method to fade in and fade out an element.

Like hide(), show() and toggle there is fadeIn(),fadeOut() and fadeToggle() methods which hides/shows and toggle the visible state of the element respectively but with a fade-out and fade-in animation. Syntax for these methods are similar with the methods above. i.e. these methods accepts 2 optional parameters speed and callback and speed parameter also accepts "slow", "fast" and millisecond value like the methods above.

There is one more method fadeTo(). It takes an additional parameter 'opacity', and change the opacity of the element to the value supplied. This method fades out the element but does not make that totally invisible if a non zero value is given as opacity.

Syntax of these methods are:

  • $(selector).fadeOut(speed,callback);
  • $(selector).fadeIn(speed,callback);
  • $(selector).fadeToggle(speed,callback);
  • $(selector).fadeTo(speed,opacity,callback);

Refer the Following Example which uses these methods using a speed value of 5000 millisecond.


<html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="divContent">Content Div</div>
    <br/>  
    <button id="btn1">Hide</button>
    <button id="btn2">Show</button>
    <button id="btn3">Toggle</button>
    <button id="btn4">Fade To</button>
    <script>
        $( "#btn1" ).click(function(){
            $("#divContent").fadeOut(5000,function(){
                alert("Fade out Clicked");
            });
        });
        $( "#btn2" ).click(function(){
            $("#divContent").fadeIn(5000,function(){
                alert("Fade in Clicked");
            });
        });
        $( "#btn3" ).click(function(){
            $("#divContent").fadeToggle(5000,function(){
                alert("Fade Toggle Clicked");
            });
        });
        $( "#btn4" ).click(function(){
            $("#divContent").fadeTo(5000,0.2,function(){
                alert("Fade Toggle Clicked");
            });
        });
    </script>
    </body>

</html>



Sliding:

Like fading we can also create a sliding animation with the selected element. jQuery provides 3 methods for sliding animation : slideUp() ,slideDown() and slideToggle(). The syntax and behaviour of these methods are similar to the fading animation methods. These methods hides/shows or toggle between hiding and showing the element with slide animation. We can control the speed of the animation and can create any custom behaviour after the animation completion using the callback parameter. The syntax is:
  • $(selector).slideUp(speed,callback);
  • $(selector).slideDown(speed,callback);
  • $(selector).slideToggle(speed,callback);
Refer the Following Example which uses these methods using a speed value of 3000 millisecond.

<html>
<head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="divContent">Content Div</div>
    <br/>  
    <button id="btn1">Slide Up</button>
    <button id="btn2">Slide Down</button>
    <button id="btn3">Toggle</button>
    <script>
        $( "#btn1" ).click(function(){
            $("#divContent").slideUp(3000,function(){
                alert("Slide Up Clicked");
            });
        });
        $( "#btn2" ).click(function(){
            $("#divContent").slideDown(3000,function(){
                alert("Slide Down Clicked");
            });
        });
        $( "#btn3" ).click(function(){
            $("#divContent").slideToggle(3000,function(){
                alert("Slide Toggle Clicked");
            });
        });
    </script>
    </body>

</html>

Custom Animation

So far we have used the built in methods to animate DOM elements. There are basic things like fading and sliding of elements that we can do using these methods. Though these basic animations are easy to use and quite useful, but we may need some more complex animations. jQuery provides a way to do almost any animation using its animate() method.

With this method the whole control is in developers hand and using different css property we can achieve complex animations like bouncing,spinning,vibrating of elements.

The animate() method takes 3 parameters, and its syntax is: 
$(selector).animate(css,speed,callback);

The first parameter is a required parameter, and here we can pass a map of css properties that we wish to alter, the 2nd and third parameters are optional and works very similar to the built-in animation methods like fading and sliding discussed above.

Let's try with an example, where we will try to create a bouncing div, Refer the following example:


<html>
<head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="divContent"style="height: 30px; width: 100px; background-color: #ffaaee; position: absolute;">Content Div</div>
    <br/>
    <button id="btn1">Animate</button>   
    <script>
        $( "#btn1" ).click(function(){
            $("#divContent").animate({ "top" : "400px" }, 500);
            $("#divContent").animate({ "top" : "50px" }, 500);
            $("#divContent").animate({ "top" : "400px" }, 500);
            $("#divContent").animate({ "top" : "100px" }, 500);
            $("#divContent").animate({ "top" : "400px" }, 500);
            $("#divContent").animate({ "top" : "200px" }, 500);
            $("#divContent").animate({ "top" : "400px" }, 500);           
        });
    </script>
    </body>

</html>

Here we have a div with fixed height and width and its position as absolute. on clicking of the button we are applying a css property "top:400px", This will position the div 400px from the top of the screen, also as we have given 500 as the 2nd parameter this re-positioning of the div will take 500 milliseconds. In the subsequent lines we have varied the css property "top" in such a way that the div will animate and create a bouncing effect.

One important note is jQuery uses queue functionality for animations so all the lines in the above example executes one after another to create the bouncing effect.Also, like the top property we can change almost all the css property according to out requirement, but one important thing is we have to use all these property names as camel cased without any '-'. i.e We need to write paddingLeft instead of padding-left, marginRight instead of margin-right.

Let's look at another example of sliding a box left to right using the callback function:


<html>
<head>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="divContent"style="height: 30px; width: 100px; background-color: #ffaaee; position: absolute;">Content Div</div>
    <br/>
    <button id="btn1">Animate</button>    
    <script>
        $( "#btn1" ).click(function(){           
            $("#divContent").animate(
                { "left" : "100px" },
                1000,
                function()
                {
                    $(this).animate(
                        { "left" : "20px" },
                        500,
                        function()
                        {
                            $(this).animate({ "left" : "50px" }, 500);
                        }
                    )
                }
            );
        });
    </script>
    </body>

</html>

Like these example we can do many more things by changing the css properties of the selected element like blinking and spinning of an element.

Stopping animation

We have seen different ways to animate DOM elements. Whether custom animation using the animate() method or animations using the in build methods like slide and fade we may need to stop the animation before it is complete. To stop an animation jQuery provides the stop() method. This works for all effects related jQuery functions, including sliding, fading and custom animations with the animate() method.

We can control the behaviour of the animation further, by choosing to stop the animation immediately or the animation to be finished and stop. By default the stop() method stops the animation immediately. There are 2 optional boolean parameters. 
The first parameter is false by default, but if we pass a true value then the animation queue (explained in the section above) will be cleared.
The second parameter is also false by default but when passed a true value this will not stop the animation immediately , but will rush to complete that ongoing animation and then stop.

Next: 

So these basic animations are handy and easy to use. Though creating complex animation seem a bit overwhelming, but since there is no need of additional resource loading (animated images/ flash files) animation using jQuery is faster and does not require additional browser plugins.
So, hope we have got the idea of creating effects using jQuery. Go through my earlier posts for understanding about the jQuery selector, events, ways to manipulate DOM. For more in built-in jQuery api on effects visit link.

Comments

  1. Howdy just wanted to give you a quick heads up and let you know a few of the images aren't loading correctly. I'm not sure why but I think its a linking issue. I've tried it in two different web browsers and both show the same results.

    ReplyDelete

Post a Comment

Popular posts from this blog

Handling Events in jQuery – Few Advanced Notes and Faqs

Ways to select DOM element(s) - a guide to jQuery Selectors

Let's traverse through DOM Tree - Few advanced notes on jQuery Selectors