AJAX and animation with jQuery

I wanted to write a short tutorial on how to utilize jQuery to create an animated AJAX page load. I hope to show off a few modern web development trends:

  • Unobtrusive JavaScript
  • JavaScript that fails gracefully
  • AJAX

A quick note: what I’m about to write would make a lot more sense inside a web framework, where whole pages aren’t loaded, but rather views (in an MVC framework). This way your AJAX call is only loading a view, or small part of HTML, rather than an entire page with a new doctype and so on.

Let’s write a normal anchor tag that will link us to a new page:

<a href="/link/to/newpage.php" id="ajax-link">Go to new page</a>

Now, we can use jQuery to spruce up this link and load in the actual page via AJAX:


	$(document).ready(function(){
		//setup click event function
		$("#ajax-link").click(function(e){
			var el = $(this); //get the clicked element
			var href = el.attr("href"); //grab clicked element's href
			$.ajax({
				type: "GET", //GET just for example, could also POST
				url: href, //request href
				success: function(response){
					el.after('<div id="ajax-container"></div>'); //create an empty div after the clicked element
					//animate ajax-container that will contain the response and append response to this container as a callback
					$("#ajax-container").animate({ height: 100, width: 300 }, 1000, function(){ $(this).append(response);});
				}
			});
			return false; //or e.preventDefault();
		});
	});

Hopefully the code is commented well enough to follow. Otherwise, here is a quick breakdown:

  1. we attach a function to the click event for our link with id “ajax-link”
  2. this function grabs the calling link’s href and performs a GET request for that resource
  3. the response from the GET request is the HTML of the particular page we are requesting — this is why this technique would work best in an MVC framework, where we could load just a partial or a view instead of an entire layout
  4. the response HTML is loaded into a container that is appended after the link
  5. then the default action of the link is prevented by returning false (or calling e.preventDefault()).

This particular animation/AJAX method will fail gracefully. If JavaScript is disabled, the user will simply navigate to the page.

Demo.

No Comments
June 22, 2009 in Development

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>