Latest TweetsDifference between mod_alias and mod_rewrite perishablepress.com/difference…
Perishable Press

Ajax Slide & Fade Content with jQuery

I recently redesigned my business site, Monzilla Media. The new design features a clean and simple single-page, fixed-sidebar layout. Visitors use the various links in the fixed sidebar to quickly and automatically scroll through to any section. In the Portfolio section, each item contains a “Details” link that loads more content into the fixed sidebar. As the site is mostly static, I wanted this bit of functionality to really shine, and after much testing and tweaking, ended up with a cross-browser slide & fade technique for loading content via Ajax and jQuery. Note this technique has been updated to work with jQuery 1.10.

Demo

Here is a live demo of Ajax Slide & Fade Content.

How it works

This technique uses jQuery to load HTML/content into a target element, such as a <div>. The nifty part is how the content is loaded/replaced with a cool slide-open, fade-in effect as the user clicks the designated links. Here is the order of events:

  1. User clicks on one of the menu links
  2. The target <div> slides open
  3. HTML/content is loaded with a fade-in effect
  4. Optional: content is highlighted with color after fade-in
  5. User clicks on another menu link
  6. Target <div> slides up and content fades out
  7. Target <div> slides open and new content is loaded with a fade-in effect
  8. Optional: content is highlighted with color after fade-in
  9. User clicks another link, etc.

Here again is the live demo of this technique, so you can see it action. Surprisingly, this functionality is achieved using a small slice of jQuery and an optional loading.gif file that’s displayed before content loads.

Quick Overview

This technique employs the following assets:

  • JavaScript Library: jQuery
  • jQuery Plugin: jQuery Color Fade (optional)
  • A slice of jQuery code
  • Some HTML/content to load
  • A small animated loading.gif image (optional)
  • A slice of CSS for the loading image (optional)

The Color Fade plugin is optional and is used to highlight the ajax content after it fades into view. It’s a sizable script, but it really adds a nice effect that helps the user to better focus on the loaded content. Without that optional effect, this technique is accomplished using a few lines of jQuery. The CSS is also optional and is used to center the loading.gif. You may follow along with the tutorial or skip to the download for rapid deployment.

Step 1: jQuery

The first step is to add the JavaScript/jQuery to the <head> section:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://example.com/slide-fade-content/jquery.colorfade.min.js"></script>

<script type="text/javascript">
// slide & fade content @ https://m0n.co/r
$(document).ready(function() {
	$('.more').on('click', function(e) {
		e.preventDefault();
		var href = $(this).attr('href');
		if ($('#ajax').is(':visible')) {
			$('#ajax').css({ display:'block' }).animate({ height:'0' }).empty();
		}
		$('#ajax').css({ display:'block' }).animate({ height:'200px' },function() {
			$('#ajax').html('<img id="loader" src="http://example.com/loader.gif">');
			$('#loader').css({ border:'none', position:'relative', top:'24px', left:'48px', boxShadow:'none' });
			$('#ajax').load('http://example.com/slide-fade-content.html ' + href, function() {
				$('#ajax').hide().fadeIn('slow').colorFade({ 'fadeColor': 'rgb(253,253,175)' });
			});
		});
	});
});
</script>

Code breakdown:

  • Include jQuery Library
  • Include jQuery Color Fade plugin (optional, edit file path as needed)
  • When the page is ready, execute the function upon click of any .more link
  • For each link click, store the href attribute as a variable
  • If the target <div> contains loaded content, slide shut and empty
  • For first clicked link, slide open #ajax <div> to 200px (adjust as needed)
  • After sliding open, display loading.gif (optional, edit path as needed)
  • Load content from external HTML via fade-in effect (edit path as needed)
  • After fading in, highlight the new content with a yellow background color (rgb(253,253,175) = #fdfcad) (also optional)

So to sum up, after including this code into your <head> section, edit the file path for the Color Fade plugin, the loading.gif image, and the HTML file. Also remember to adjust the height:'200px' value according to your design. Also, there are two optional items; here is how to remove/omit either of them:

Omit the loading.gif file

Remove the following lines:

$('#ajax').html('<img id="loader" src="http://example.com/loader.gif">');
$('#loader').css({ border:'none', position:'relative', top:'24px', left:'48px', boxShadow:'none' });

Omit the Color Fade plugin

  1. Remove the link to the Color Fade plugin
  2. Remove “.colorFade({ 'fadeColor': 'rgb(253,253,175)' })

Improvements

One improvement I would like to make with this technique is to eliminate the need for the height calculation. I’ve tried using jQuery’s .slideUp/.slideDown functionality, but couldn’t get it to work. If you have any ideas for this, please share in the Comments.

Step 2: HTML

There are two things we need for the HTML. The first is the content that you want to load. For this tutorial, we’ll just use some boring old Lorem Ipsum text to keep things simple. In your blank HTML file, include the following markup:

<div id="load">
	<div id="first-item">
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
	</div>
	<div id="second-item">
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
	</div>
	<div id="third-item">
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus hendrerit. Pellentesque aliquet nibh nec urna. In nisi neque, aliquet vel, dapibus id, mattis vel, nisi. Sed pretium, ligula sollicitudin laoreet viverra, tortor libero sodales leo, eget blandit nunc tortor eu nibh. Nullam mollis. Ut justo. Suspendisse potenti.</p>
	</div>
</div>

Each click menu link will load one of these content sections into the ajax <div> on your web page. You may add this <div> to the location in your page where you want the loaded content to appear:

<div id="ajax"></div>

The last thing we need to do for the HTML part of the tutorial is to include some links to trigger the loading of your new content. Here is a basic example to place anywhere in your web page:

<ul>
	<li><a class="more" href="#first-item">First Item</a></li>
	<li><a class="more" href="#second-item">Second Item</a></li>
	<li><a class="more" href="#third-item">Third Item</a></li>
</ul>

These links each contain a more class, so when clicked, the script will use the href value to load the corresponding section of content from the external HTML file. So you can use any link(s) you want to trigger the loading of new content. Just slap a class="more" on there and make sure the href value matches the content’s id attribute in your content file.

Step 3: CSS + loading image

At this point, the slide-&-fade functionality should be working great. The last step is to upload the loading.gif file and style it with a little CSS:

<style type="text/css">
.loader { border: 0 none; float: left; clear: both; margin: 100px 0 0 200px; }
</style>

This style snippet attempts to position the loading image more toward the center of the ajax <div>. You may need to tweak the left margin (200px) depending on how wide the ajax <div> displays in your design.

Troubleshooting

Here are some things to check if the technique isn’t isn’t working:

  • Double-check that the assets are in place
  • Double-check the file paths to the different assets
  • Make sure jQuery is included only once on the page
  • Make sure jQuery is included before the slide/fade code
  • Check for any interfering scripts or alternate JavaScript libraries

You may also want to check out the demo or my business site to see it working and maybe help pinpoint any issues.

Download

Here you can download the source files for Ajax Slide and Fade Content.

Ajax Slide & Fade Content – Version 2.0 (9 KB zip)

Jeff Starr
About the Author Jeff Starr = Creative thinker. Passionate about free and open Web.
Archives
35 responses
  1. Forgot to wrap with code tag… oops

  2. Michael Poepperl May 25, 2012 @ 9:37 am

    I fixed your problem with the height calculation!

    INSERT “100%” no 200px – USE 100% and it works

    best regards,
    Michael

  3. Travis Hawkins July 17, 2012 @ 2:57 pm

    Is it possible to have the 1st item show when the page loads ?

  4. Great tutorial!

    Before I implement this technique to my current project, I would appreciate it if you could tell me if the content fader could be implemented for multiple pages too?

    I’m a little concerned about this line

    $(‘#ajax’).load(‘slide-fade-content.html #’+href,function(){

    You can watch my project here:

    http://www.ascreamingsymphony.com/ASS

    Thanks in advance!
    Marc

  5. how to convert script to work with jquery 1.7.1?

  6. Hello!
    I had installed this effect a few weeks back with no real issues, but now when I testing the site for a launch I ge the error :

    “A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete.

    Script: http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js:2

    I am wondering if there is an update, or if this is a known issue/bug?

    Thanks!

  7. Is it possible to have the 1st item show when the page loads ?

  8. It’s worth taking a look at what happens to your page with JS off. Eek, not good. JS should be used to enhance content rather than to serve it.

  9. Thanks for this tutorial, Jeff … it’s a great effect. I think I’m in a bit over my head, though, because your demo works a lot better and more smoothly than my own application. Clicking the first item link works as intended, with the external content sliding into place nicely. But clicking subsequent links causes the entire content area of the page to jump to the top before settling down into place. The correct external content does fill the ajax area, but the transition is unacceptable jumpy and a little violent. Here’s my page … you’ll be able to see what I mean.

    http://www.designerbath.com/content/products-dev/test.html

    Any thoughts on what I’m doing wrong? I’d appreciate the benefits of your expertise.

    Thanks again.

    Jack White
    A Streetcar Named Design

  10. Robert Wilkins October 18, 2012 @ 2:32 pm

    Is it possible to have the ajax external html content load beneath each list item rather than beneath the ? I understand that the is a block but it reads so much more naturally, when there is a answer to the question next to it rather than a few hundred pixels away.

    Thanks…

  11. Robert Wilkins October 18, 2012 @ 7:04 pm

    Thanks Jeff. sorry for the basic question .toggle() sounds like the way to go. Can you show a quick example of where I apply this in your javascript? I’ve seen examples of the code but can’t figure out how to plug it into yours.

  12. Jeff-

    Great tutorial! This was exactly what I was looking for! I do have one question though. Is there a way to display content upon page load? Instead of having to click a link first to load some content.

    Thanks again for sharing!

[ Comments are closed for this post ]