Wednesday, October 9, 2024

jQuery Basics for Web Developers: Animation

In the last article, we talked about some effects you can add to your web site using jQuery. In this article, we will look into more animations that can be accomplished. These are a little more advanced than a simple hide or show type effect.

Animate Your Website

The jQuery animate method creates animation effects on CSS properties. The CSS properties must be numeric properties. The animate method adds or subtracts the numeric value provided from the current numeric value. If you set a font-size to 10px in your page’s CSS section and then set it to increase to 30px in the jQuery animate method, jQuery will increase the font-size from 10px to 30px gradually. This gives you the animated effect that the font has grown larger. The basic syntax is this:

	.animate({<css property> : <value>})
		

An example:

    $("#AnimateMe").animate({"font-size" : "30px"})
        

The above example applies the CSS property, "font-size", to the HTML element with an ID of "AnimateMe". What this does is increases the font-size to 30 pixels gradually.

Here is a complete code example to show case the example:

    <html>
	    <head>
		    <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
		    <script type="text/javascript">
			    $(document).ready(function(){
			     $("#ClickMe").click(function () {
			     $("#AnimateMe").animate({
     "font-size" : "30px"
					    });
				    });
			    });
		    </script>
	    </head>
	    <body>
		    <p><input type="button" value="Click Me" id="ClickMe" /></p>
		    <p id="AnimateMe">Did I animate?</p>
	    </body>
    </html>
        

When the button is clicked, the text should get larger.

CSS Properties

The above example showed how you could make a font animate larger, but you can do many other animations by manipulating CSS properties. If we change the above line (in the HTML code) from:

    $("#AnimateMe").animate({
        "font-size" : "30px"
    });
        

To:

    $("#AnimateMe").animate({
        "opacity" : "0"
    });
        

It will cause the text to gradually disappear. This will set the opacity from 100% to 0% gradually. If we change it to:

    $("#AnimateMe").animate({
        "margin-left" : "100px"
    });
        

It will move the text over 100 pixels from the left.

As you can see, there a many ways you can animate a HTML element. jQuery takes care of the in between calculations.

As stated before, property values must be numeric. A property value like "color" cannot be animated without a plugin like the jQuery UI Library (more on that in the future). Property values can also take these keywords: "show", "hide", and "toggle". These keywords are custom hiding and showing animations.

Property values can also be made relative by using the "+=" or "-=" added to the beginning of the property value. If we add the "+=" to the property value in the above HTML code, it will increase the font-size by 30 pixels every time the button is pressed. Before, it would only increase it one time.

    $("#AnimateMe").animate({
        "font-size" : "+=30px"
    });
        

Now every time you press the button, the text grows by 30 pixels. You can get the opposite effect (shrink it), by using the "-=". You can also add the "+=" to the margin property above to make the text move 30 pixels to the left every time the button is pressed.

Setting the Animation Duration

You can control the duration of the animation by specifying a value in milliseconds. A higher value produces a slower animation. You can also use the keywords "slow" and "fast" which translate to "600" and "200" milliseconds. Here is the syntax:

    .animate({<css property> : <value>}, duration)
        

An example:

    $("#AnimateMe").animate({"font-size" : "30px"}, "slow")
        

Try adding the "slow" keyword to the HTML file above and see how it works. An example:

    $("#AnimateMe").animate({
        "font-size" : "+=30px"
    }, "slow");
        

Callback Function

Another feature of the animate method is that you can call a function that executes when the animation is complete. Here is the syntax:

    .animate({<css property> : <value>}, duration, function)
        

An example:

    $("#AnimateMe").animate({"font-size" : "30px"}, "slow", function() {alert("Done")})
        

Conclusion

As you can see, there are a few different ways to use jQuery to animate the HTML elements on your page. The following code shows how you can use jQuery to create different animations. To use this, you will need to create an HTML file on your computer and copy this code into it (or just try it in our Test the Code box below—just give everything time to load before you try out the effects). You should then be able to run it from your PC.

    <html>
        <head>
            <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function () {
                    $("#BiggerText").click(function () {
                        $("#BiggerTextAnimate").animate({
                            "font-size": "30px"
                        });
                    });

                $("#MoveBoxLeft").click(function () {
                    $("#Box").animate({
                        "margin-left": "+=30px"
                    });
                });

                $("#MakeBoxDisapper").click(function () {
                    $("#Box2").animate({
                        "opacity": "0"
                    }, function () {
                            alert("Is this box gone?");
                        });
                    });
                });
            </script>
        </head>
        <body>
            <p><input type="button" value="Make the text bigger" id="BiggerText" /></p>
            <p id="BiggerTextAnimate">Did I get bigger?</p>
            <p><input type="button" value="Move the box to the left" id="MoveBoxLeft" /></p>
            <div id="Box" style="background-color: Black; width: 100px; height: 100px;">&nbsp;</div>
            <p><input type="button" value="Animate the box below and execute a function" id="MakeBoxDisapper" /></p>
            <div id="Box2" style="background-color: Black; width: 100px; height: 100px;">&nbsp;</div>
        </body>
    </html>
        



Test the Code




Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured