Login | Register | FAQ
Anonymous


Lesson 20: Cool Animation Effects with jQuery

By Maria Antonietta Perna

jQuery is so rich with ready-made functions that adding fancy effects on your web page is a breeze. It's hard not to get carried away with it.

Here, we are going to explore the most commonly used jQuery effects. Once again, my recommendation is that of integrating this lesson with a visit to the jQuery website for more code samples and detailed explanations.

In this lesson you will learn how to:

  • add effects by dynamically manipulating styles;
  • use jQuery's show()/hide()/toggle() methods;
  • use jQuery's fadeIn()/fadeOut()/fadeToggle() methods;
  • use jQuery's slideUp()/slideDown()/slideToggle() methods.

In the process, you will build a simple sliding menu and get more practice with the new jQuery approach.

How do I add and remove CSS classes with jQuery?

jQuery enables you to manipulate CSS styles in code with $.css(styleName, styleValue). It also enables you to add and remove CSS classes in relation to DOM elements.

Because $.css() would sprinkle your HTML page with inline CSS style rules, we will focus on applying and removing CSS classes with $.addClass(className), $.removeClass(className), and $.toggleClass(className). This approach uses the CSS class declarations stored either in the <head> of your HTML page or in a separate file, therefore it's better suited to current best practices in web design.

If you're curious about $.css(), by all means visit http://api.jquery.com/css/ for more details.

Suppose you want to replace the CSS class bigDiv with the CSS class smallDiv when the user clicks inside the div element. This is how you could do the task with jQuery:

		
		$(document).ready(function()
		
		{
		
		//Store a reference to the div in a variable using its id:
		
		var myDiv = $('#myDiv');
		
		//Attach a click handler to manipulate the CSS classes:
		
		myDiv.click(function()
		
		{
		
		//Remove the existing CSS class and replace it with the new one.
		
		//Because the element is the same, chain both methods:
		
		myDiv.removeClass('bigDiv').addClass('smallDiv');
		
		});
		
		});
		
		

What about toggling between the CSS bigDiv and smallDiv classes by clicking inside the div? That's easy: jQuery has this little handy method for you - $.toggleClass(). Assuming the CSS class bigDiv is hard-coded in the class attribute of the div element, you can toggle the CSS class smallDiv using jQuery, like so:

		
		$(document).ready(function()
		
		{
		
		var myDiv = $('#myDiv');
		
		myDiv.click(function()
		
		{
		
		myDiv.toggleClass('smallDiv');
		
		});
		
		});
		
		

Now, keep clicking inside the div element, and you'll see it getting smaller and bigger at each click of the mouse.

How do I use jQuery show()/hide()?

If you want to show/hide HTML elements on a page, you can do so easily with jQuery's show()/hide(). You can also modulate the way elements are revealed or hidden by adding the 'slow' or 'fast' arguments, or even the number of milliseconds you'd like the transition to last.

Let's say you have a paragraph element inside a div with an id of myDiv. You want the paragraph to slowly disappear when the user clicks inside the div element. Here's how you could accomplish this with jQuery hide().

		
		$(document).ready(function()
		
		{
		
		var myDiv = $('#myDiv');
		
		myDiv.click(function()
		
		{
		
		//Replace 'slow' with 2000 for a slower transition.
		
		$('p').hide('slow');
		
		});
		
		});
		
		

Clicking inside the div element results in the paragraph slowly disappearing from view. jQuery show() works the same way. I leave you to experiment with it on your own.

What if you wanted to toggle between show/hide transitions as the user clicks inside the div element? No problem, jQuery offers the $.toggle() method. To see it in action, simply replace hide() with toggle() in the previous example, like so.

		
		$(document).ready(function()
		
		{
		
		var myDiv = $('#myDiv');
		
		myDiv.click(function()
		
		{
		
		$('p').toggle('slow');
		
		});
		
		});
		
		

How do I make DOM elements fade in and out of the page?

For a more sophisticated fading effect, use $.fadeIn()/$.fadeOut()/$.fadeToggle(). You use these methods the same way as you used $.show()/$.hide()/$.toggle() in the previous examples.

Here's the paragraph from the previous code sample toggling between visible and hidden using $.fadeToggle().

		
		$(document).ready(function()
		
		{
		
		var myDiv = $('#myDiv');
		
		myDiv.click(function()
		
		{
		
		$('p').fadeToggle('slow');
		
		});
		
		});
		
		

The effect is very similar to that of $.toggle('slow'). Just try it out.

How do I make DOM elements slide up and down with jQuery?

You can easily make DOM elements appear and disappear with a sliding effect using $.slideUp()/$.slideDown()/$.slideToggle(). You implement these methods similarly to the previous ones.

For example, let's say you want to slide the paragraph element from the previous example up and down as the user clicks inside the div element. Here's how you would accomplish this with $.slideToggle().

		
		$(document).ready(function()
		
		{
		
		var myDiv = $('#myDiv');
		
		myDiv.click(function()
		
		{
		
		$('p').slideToggle('slow');
		
		});
		
		});
		
		

Now keep clicking inside the div element and see the paragraph inside the div sliding up and down.

I recommend you experiment with the code samples above as much as you can before moving on with the next challenge.

Try out: sliding menu

Here we are at our jQuery try out exercise. You will build a simple sliding menu similar to what you might have already seen on many websites.

The user moves the mouse over a main menu item and a list of sub-menu items slides down. As the user moves the mouse away from the menu item, its sub-menu items slide back up away from view.

Let's start from the HTML page:

		
		<!DOCTYPE html>
		<html>
		<head>
		<title>Lesson 20: jQuery Sliding Menu</title>
		
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
		
		<script type="text/javascript" src="lesson20_ex.js"></script>
		
		</head>
		<body>
		<h1>Lesson 20: jQuery Sliding Menu</h1>
		
		<div id="myDiv">
		
		<ul class="outerList">
		<li><a href="#">Menu Item 1</a></li>
		<li><a href="#">Menu Item 2 ↓</a>
		
		<div>
		<ul class="innerList">
		<li><a href="#">Sub-Menu Item 1</a></li>
		<li><a href="#">Sub-Menu Item 2</a></li>
		<li><a href="#">Sub-Menu Item 3</a></li>
		</ul>
		</div>
		
		</li>
		<li><a href="#">Menu Item 3</a></li>
		</ul>
		
		</div>
			
		</body>
		</html>
		
		

The HTML page above has a reference to a CDN-served copy of jQuery and to an external JavaScript file in the <head> section.

The <body> section has a div element with an id of myDiv that contains a list with 3 main menu items and 3 sub-menu items nested inside the second main menu item. The sub-menu items are contained inside a div element.

Style your menu so that the main menu items are horizontally lined up and the nested sub-menu items are vertically stacked under their parent li element (take a peek at the example page if you like).

We want the div element that wraps the sub-menu items to slide down when the user moves the mouse over its parent li element.

Prepare your lesson24_ex.js file and write the following code.

		
		$(document).ready(function()
		
		{
		
		//retrieve the menu subitems (div element child of the list element)
		
		//with the powerful jQuery selectors
		
		//and store them in a variable
		
		var subItems = $('ul li div');
		
		//retrieve the main menu items that
		
		//have the retrieved subitems as children.
		
		//Notice the handy .has() method:
		
		var mainItems = $('ul li').has(subItems);
		
		//Hide all subitems on page load
		
		subItems.hide();
		
		//Attach the .hover() function to the main
		
		//menu items:
		
		$(mainItems).hover(function()
		
		{
		
		//Apply .slideToggle() to the sub-menu
		
		subItems.slideToggle('fast');
		
		});
		
		});
		
		

Save your work and preview it in a browser. You should see something like the page indicated by following the example link above, only reflecting your own CSS styles.

Move your mouse over the second menu item and if all goes as expected you'll see the sub-menu sliding down. It's taken us just a few lines of code to accomplish an animation effect that in raw JavaScript would have made us sweat quite a bit.

Summary

You've achieved a lot in this lesson. You know how to use several jQuery functions to manipulate styles. Also, you know how to add fancy effects to your web pages with very little code. Finally, you put your new knowledge to the test by building a core website component - a horizontal sliding menu - using jQuery.

I still advise you to pop over to the jQuery website for a detailed coverage of everything this fabulous library has to offer.

Our next lesson revisits a topic we covered back in lesson 18, get ready for AJAX done the jQuery way.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 19: Short Introduction to jQuery

Lesson 21: Easy AJAX Calls with jQuery >>