Over a million developers have joined DZone.

Native jQuery animations

· Web Dev Zone

Make the transition to Node.js if you are a Java, PHP, Rails or .NET developer with these resources to help jumpstart your Node.js knowledge plus pick up some development tips.  Brought to you in partnership with IBM.

jQuery is probably the most diffused JavaScript library in the world, and its focus on simplicity gave it the success it experiences now.

jQuery has a wide set of plugins for user interface design, but it forces you to include no more than its single base source file to gain the capability of creating cross-browser smooth animations.

Since you probably already have heard a lot on the benefits of jQuery due to the lot of buzz around it, I'll dive into the code. All the code samples are functional and tested in Firefox 3.6: you can paste them into an empty HTML file and start hacking on JavaScript and jQuery right away. I assume you already have a very basic knowledge of jQuery and JavaScript, since explaining anonymous functions here will be out of the scope of this article.

Hiding and showing

The first example is the simplest one, and it will serve to introduce the jQuery infrastructure and get a running animation. We dynamically insert a button which, when clicked, hide or show the paragraph it is associated to. In jQuery jargon, this action is called toggling.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('<button>Toggle</button>').click(function() {
$('p#showHide').toggle();
}).insertBefore('p#showHide');
});
</script>
</head>
<body>
<p id="showHide">I will be shown or hidden.</p>
</body>
</html>

Like many other JavaScript frameworks, jQuery can be included by linking to its most recent 1.x version on the Google CDN (no need to upload any .js files to your server). jQuery has a Facade, the jQuery object, which can be used to access all the functionalities we need. An alias for the jQuery object is the $ global variable. Global variable sound strange, but in JavaScript it is a pretty common pattern.

When an anonymous function is passed to the $ Facade, it will be executed when the document is fully loaded. Our function creates a button (this is what happen when you pass an HTML string to $), and associates to its onclick event a call to the toggle() method, which will show or hide the paragraph selected, depending on its current state. Finally, we chain a call to insertBefore() after the one at click(), to insert the button in the DOM.

Hiding and showing (improved)

toggle() can actually take functions as arguments. When this is the case, it will cycle between the various functions, executing one at each click on the element it is called on.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var button = $('<button>Hide</button>').toggle(function() {
$('p#showHide').hide();
button.text('Show');
},
function() {
$('p#showHide').show();
button.text('Hide');
}).insertBefore('p#showHide');
});
</script>
</head>
<body>
<p id="showHide">I will be shown or hidden.</p>
</body>
</html>

The first function hides the paragraph and change the text of the button. The second one does the same, but with the opposite intent.

Fading

Fading is operating on an element's opacity, to make it vanish or appear. Elements that fade out disappear gracefully, with a smooth transition that replace the simple hiding and showing we set up earlier.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var button = $('<button>Hide</button>').toggle(function() {
$('p#showHide').fadeOut();
button.text('Show');
},
function() {
$('p#showHide').text('I\'m coming back...');
$('p#showHide').fadeIn(10000, function() {
$('p#showHide').text('I\'m back from the dead.');
});
button.text('Hide');
}).insertBefore('p#showHide');
});
</script>
</head>
<body>
<p id="showHide">I will be faded out by manipulation of my opacity.</p>
</body>
</html>

Many jQuery functions take callbacks as arguments. Every JavaScript API is asynchronous and functions like fadeOut() return immediately after you call them, even if the transition is still running (in this case, it takes 10 seconds.) However, you can pass a callback that will be executed on completion.

Sliding

What we can do with fading, we can also do with sliding. Elements that slide out slip under the previous elements, freeing space on the page.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var button = $('<button>Hide</button>').toggle(function() {
$('p#showHide').slideUp(5000);
button.text('Show');
},
function() {
$('p#showHide').text('I\'m coming back...');
$('p#showHide').slideDown('normal', function() {
$('p#showHide').text('I\'m back from the dead.');
});
button.text('Hide');
}).insertBefore('p#showHide');
});
</script>
</head>
<body>
<p id="showHide">I will slowly slide up and hide.</p>
</body>
</html>

Again, we can specify durations with strings like 'slow', 'normal' and 'fast', or via milliseconds.

Custom animation

When the ordinary animation don't cut it, we can resort to the animate() method, which produces transition on numeric CSS properties. We simply specify the target of the properties we want to reach after the animation.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#animated').animate({
'height' : '200px',
'width' : '200px'
});
});
</script>
</head>
<body>
<p id="animated" style="background-color: gray;">I will be animated.</p>
</body>
</html>

Toggling animations

Of course we can put all together, and toggling different hiding/showing animations.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var button = $('<button>Restrict</button>').toggle(
function() {
button.text('Enlarge');
$('#animated').animate({
'height' : '200px',
'width' : '200px'
});
},
function() {
button.text('Restrict');
$('#animated').animate({
'height' : '400px',
'width' : '400px'
});
}).insertBefore('#animated');
});
</script>
</head>
<body>
<p id="animated" style="height: 400px; width: 400px; background-color: gray;">I will be animated.</p>
</body>
</html>

Custom animations durations and callbacks

Custom animations can also accept different options, like durations in milliseconds or as a keyword, or callback to execute on completion.

<html>
<head>
<title>jQuery animations</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var button = $('<button>Restrict</button>').toggle(
function() {
button.text('Enlarge slowly');
$('#animated').animate({
'height' : '200px',
'width' : '200px'
});
},
function() {
button.text('Restrict');
$('#animated').animate({
'height' : '400px',
'width' : '400px'
}, {
duration: 10000,
complete: function() {
$('#animated').animate({
'font-size' : '20px'
})
}
});
}
).insertBefore('#animated');
});
</script>
</head>
<body>
<p id="animated" style="height: 400px; width: 400px; background-color: gray;">I will be animated.</p>
</body>
</html>

Conclusion

I hope this was a good panoramic of jQuery native capabilities for animation of HTML pages. Sometimes methods are very overloaded, like in the case of $ or toggle(), but jQuery has very good documentation and I encourage you to refer to the official API to fully learn what jQuery is capable of.

Learn why developers are gravitating towards Node and its ability to retain and leverage the skills of JavaScript developers and the ability to deliver projects faster than other languages can.  Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}