Useful Resources for Web Designers and Developers

Advertise

here through BuySellAds

Yet Another jQuery Accordion Tutorial

November 6, 2010 on General, Tutorials

It just about that time some good old fashioned web programming. Today we’re learning how to create an accordion style page – using my most favorite of tools: jQuery and CSS. We will try to accomplish an accordion that is so simple, yet useful enough for you to use in your existing pages. Ready to get started – let’s begin.

The Goal:

We will use clean markup. We’re trying to integrate this into exsting HTML – so we will be generating all extra classes and tags using Javascript. I imagine most web documents follow the same constant pattern: Heading tags, followed by some content which are a mixture of different DIVS, paragraphs, images etc. This goes on until the next heading tag – which is usually the same type as the first heading.

Look at the sample mark up below:

1
2
3
4
5
6
<h5>Some Heading</h5>
       <!--content in here-->
<h5>Some Heading</h5>
       <!--content in here-->
<h5>Some Heading</h5>
        <!--content in here-->

We will use the H5 tags as our “Clicker” – once clicked, will hide the contents right underneath it. Click it again, and it will show the contents again.

The Script:

We start by calling the jQuery library, followed by the document.ready() call:

1
2
3
4
5
6
7
8
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
 
               <!--script goes here-->
 
});
</script>

We then loop through each of our particular heading tag (in this case, all of H5). Once it finds all of them, it checks to see if right next to it is another H5 tag; if it’s not, it adds a class of “clicker” to it and appends a span with a minus (-) sign in it:

1
2
3
4
5
$("h5").each(function(e){
	if(!($(this).next().is("h5"))){				
	    $(this).addClass("clicker").append('<span>-</span>');				
	}					
});

If you investigate your code so far – you will see that only the H5 tags that have content OTHER than H5 tags have the class “clicker” and the span tag with a minus (-) sign in it:

accordion1 Yet Another jQuery Accordion Tutorial

Now let’s code the click events:

1
2
3
4
5
6
7
8
9
$("h5.clicker").toggle(
		function(){			
			$(this).nextUntil("h5").slideUp('slow');
			$(this).find('span').html('+');	
			},
		function(){  
			$(this).nextUntil("h5").slideDown('fast');
			$(this).find('span').html('-');	
		})

Now that we have our designated clickers, we create a couple of functions that toggle at every click.

The first action, hides the contents below “$(this)” – which is the tag you just clicked. Remember – we only want to hide the contents up until the next H5 tag. It also changes the content of the span into a plus (+) symbol.

The second action shows the contents below, and changes the span to a minus (-) symbol.

Optional Styling:

At this point you already have a functional accordion. If you’re applying the code to an existing page, you are already working with the current styles. Although, using CSS3 for say the plus (+) and minus (-) span looks pretty cool – which I’m sure you’d want to use.

Add this code to your styles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#wrap h5 span, #wrap h5 span:visited {
	background: #2daebf url(alert-overlay.png) repeat-x; 
	display: inline-block; 
	padding: 1px 9px 2px 9px; 
	color: #fff; 
	text-decoration: none;
	-moz-border-radius: 5px; 
	-webkit-border-radius: 5px;
	-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.5);
	-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.5);
	text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
	border-bottom: 1px solid rgba(0,0,0,0.25);
	position: relative;
	cursor: pointer;
	float:right;
	font-family:Arial, Helvetica, sans-serif; font-weight:bold;
	*top: -47px; /*ie 7*/
}
 
#wrap h5 span:hover{ background-color: #007d9a; color: #fff; }
#wrap h5 span:active{ top: 1px; }
#wrap h5 span, #wrap h5 span:visited { font-size: 23px; font-weight: bold; line-height: 1; text-shadow: 0 -1px 1px rgba(0,0,0,0.25);  }

Of course you have to replace the #wrap h5 with your own class / ids. This creates the css3 button you see in the demo. This code is courtesy of Zurb’s Super Awesome buttons with CSS3 and RGBA:

Conclusion

And that is it! You have yourself an accordion page powered by jQuery. Feel free to grab this code and improve it. Maybe refactor it into a more plugin like code – make it more reusable. Or even – fix the choppiness issue in the slideUp / slideDown animation in certain browsers. In any case, please leave a comment on what you think of this code.

You might also be interested in these articles regarding jQuery accordions:

There are no downloads for this tutorial because it’s pretty simple to follow. View the source code of the demo page to get the code
  • http://hardiannazief.com Dian

    Awesome! thanks :D
    It felt a bit choppy in firefox (maybe because i use a lot of plugins) but besides that, it works smoothly on ie8 and chrome :)

  • http://www.redchillimedia.com/flyers Sachin Gupta

    Nice tutorial to design jquery for flyers. Thanks..

  • kemar

    hey,
    this is a great variation. However, i noticed that in Firefox 3.6 on Windows, it’s show in collapsing and expanding as oppose IE 6, in which pretty smooth. Why is that?

  • Ronit

    Nice tutorial, Is there a way that the default state will be collapsed?

  • http://icosmin.com iCosmin

    Very slow in Firefox… I believe that looping through each heading adds to this.

    It would be faster if you, for example, only add a class to all H5s in a div and trigger the clicker function on all those H5.

    What do you think?

    • http://fearlessflyer.com michael soriano

      it is quite slow.
      the looping only happens once on doc ready. and i wanted the script to apply on existing markup. so the only real criteria i have is if an h5 has something else below it – other than another h5. since most documents follow the same format.

      let me look into speeding this thing up.

  • http://www.wordpressrehberi.com/ Mehmet – Wordpress Rehberi

    That is very helpful tutorial for me and thank you for sharing this. But I wanna ask you something that how can I make it closed as default? Thanks in advance!

    • http://fearlessflyer.com michael soriano

      you’d have to hide the elements as soon as doc is ready. $(‘selector’).hide() – something of that nature.

  • Anthony Domingo

    I sampled the demo on Chrome, IE7, and safari and it works beautifully. Did you happen to find out a cause or solution to why it is choppy in Firefox?

    • http://fearlessflyer.com michael soriano

      I haven’t had time to investigate.

  • Tina

    How can I make the default state collapsed?

    Thanks!
    Tina

  • Catherina Lucy

    Good stuff.It has a meaningful information.thanks for the share.

    http://www.accordionguide.info