DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Native jQuery animations

Native jQuery animations

Giorgio Sironi user avatar by
Giorgio Sironi
·
Aug. 18, 10 · Interview
Like (0)
Save
Tweet
Share
8.84K Views

Join the DZone community and get the full member experience.

Join For Free

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.

JQuery

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Integrate AWS Secrets Manager in Spring Boot Application
  • Choosing the Right Framework for Your Project

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: