Build a Slick and Simple MooTools Accordion

By  on  

Last week I covered a smooth, subtle MooTools effect called Kwicks. Another great MooTools creation is the Accordion, which acts like...wait for it...an accordion! Now I've never been a huge Weird Al fan so this is as close to playing an accordion as I'll get, but the MooTools accordion has been certified cool many times over.

In speaking with designers, I frequently hear how much they'd like to use an accordion on their site but they think it's either too time-consuming or that they don't have the ability to code JavaScript. Not true! To prove my point, I'll use a little MooTools magic and some easy XHTML / CSS to accomplish a slick accordion effect.

This demo will star The Beatles, Rod Stewart, and Oasis.

Step 1: The Toggler HTML

<div id="accordion">
	<h3 class="toggler">The Beatles</h3>
	<div class="element">
		<img src="https://davidwalsh.name/demo/accordion/let-it-be.jpg" class="image" />
		<p>The Beatles were a pop and rock group from Liverpool, England...</p>
	</div>
	<h3 class="toggler">Rod Stewart</h3>
	<div class="element">
		<img src="https://davidwalsh.name/demo/accordion/every-picture.jpg" class="image" />
		<p>Roderick "Rod" David Stewart, CBE (born January 10, 1945), is a singer and songwriter born and raised in London, England...</p>
	</div>
	<h3 class="toggler">Oasis</h3>
	<div class="element">
		<img src="https://davidwalsh.name/demo/accordion/oasis.jpg" class="image" />
		<p>Oasis are an English rock band that formed in Manchester in 1991. The group was formed by Liam Gallagher (lead vocals), Paul Arthurs (guitar)...</p>
	</div>
</div>

Note that each <h3> is given the toggler class. These will be the accordion toggle elements. The data elements are named "element" -- these elements will be hidden.

Step 2: The CSS

.toggler  { cursor:pointer; font-weight:bold; color:#000; margin: 0; padding:5px; font-size:16px; font-family:Arial, sans-serif; }
.toggler:hover	 { background:#eee; }
.element	 { padding:0 5px; }

Really basic CSS. For usability purposes, I've added the "pointer" cursor so that users know what to click.

Step 3: The MooTools JavaScript

window.addEvent('domready', function() {
	/* var accordion = new Accordion($$('.toggler'),$$('.element'), { pre-MooTools More */
	var accordion = new Fx.Accordion($$('.toggler'),$$('.element'), {
		opacity: 0,
		onActive: function(toggler) { toggler.setStyle('color', '#f30'); },
		onBackground: function(toggler) { toggler.setStyle('color', '#000'); }
	});
});

The MooTools Accordion class accepts three arguments:

  1. The first is the toggler elements, which we can grab with: $$('h3.toggler') or the shorter $$('.toggler')
  2. The second is the content elements, which we can grab with: $$('div.element') or the shorter $$('.element')
  3. The third is an array of options. In this accordion, I'm keeping it simple. I've turned off the opacity effect option, made the toggler text color red when it's active, and set it back to black when it's not active.

Recent Features

Incredible Demos

  • By
    Flashy FAQs Using MooTools Sliders

    I often qualify a great website by one that pay attention to detail and makes all of the "little things" seem as though much time was spent on them. Let's face it -- FAQs are as boring as they come. That is, until you...

  • By
    Use Elements as Background Images with -moz-element

    We all know that each browser vendor takes the liberty of implementing their own CSS and JavaScript features, and I'm thankful for that. Mozilla and WebKit have come out with some interesting proprietary CSS properties, and since we all know that cementing standards...

Discussion

  1. Excellent tutorial! I’ve always admired mootools, but wound up sticking with jquery because it always seemed easier. Thanks for sharing :)

  2. Yes it’s surprisingly easy isn’t it?

  3. I’m glad it was useful Erika!

  4. Brian

    Is there a way to default the tabs so that they are all closed… instead of the 1st one being open?

    thanks

    • Same place you see opacity: 0, you have a bunch of options you can use, like:

      show: 0, ( or 1, 2, 3, etc )
      display: -1, ( this I think toggles all of the tabs closed )

      There’s a full list of arguments you can add on the mootools demo site.

    • Sunnie Han

      Hi Marco,

      I am using the display:-1 to toggle all of the tabs closed. The code is in following Link, but not working:( Need help!!!!

      https://gist.github.com/cici004/9825262f6035bd4632094af93e3c23bc

  5. Patte

    Thanks for this very simple tutorial – it’s been helpful since there a lot of old tutorials on the web.

    BUT one thing still bothers me… I couldn’t get it to work with the 1.2 beta (mootools-beta-1.2b2-compatible.js) or the 1.1 version (mootools-release-1.11.js) – I didn’t forget to rename moo1.2.js but anyway… I won’t work.

    I had to download your moo1.2.js to make it work. Still it’ll be more than helpfull to figure out the offical way to make it work.

    Thanks in advance.
    -Patte

  6. @ Patte: What javascript error were you getting? I have beta 1.2.

  7. @Brian: You’ll need to set “alwaysHide” to true and set “show” equal to a number higher than the number of togglers you have.

  8. Patte

    @David: I can’t tell the error, I’m just very brand new to the whole javascript thing – that’s why your introductional description really made me feel welcome.

    I just put the page up here:

    http://dummy3.uaarg.de/slickaccordion2.html

    What I did was simply download the mootools-beta-1.2b2-compatible.js from mootools and put it as source.

    On the page is also a working one, which is using the moo1.2.js from your page.

    Like I understand the case the whole thing ought to work – but i doesn’t.
    Any ideas?

  9. @Patte: I’ll check it out later today and see what the issue could be.

  10. I’ve been pulling my hair out. I can get everything to work great with mozilla based browsers, but IE6/7 go haywire.

    You may see my example via

    http://portal2web.biz/php/mootools_accordion/

    David’s example works fine in everything I tested it with, so I’m at a loss as to what to do.

    I’ve been struggling with this for days now and I could really use a pointer or two.

    Thanks in advance, folks!

  11. @Joseph: A few things. One, you’re using Moo 1.1, not 1.2 (which my example covers). Two, you have no “wrapper” for your accordion.

    You have two options: one, use Moo 1.2:

    http://mootools.net/download/tags/1-2b2

    …or make your accordion 1.1 compliant:

    http://demos.mootools.net/Accordion

  12. RS Justin

    David,

    Thanks so much for the tutorial…to be honest, I’m somewhat of an intermediate novice n00b in the mootools world, and I’ve been looking for a good walkthrough on how to get my beloved 1.11 accordion into shape for 1.2 because some of those guys are starting to leave the old stuff behind.

    It’s bee frustrating because, as I’m sure you know, the insular jscript crowd tends to hate on folks who ask questions about the accordion. A damn shame.

    I do have one question/request…one that’s worth at the very least a case of beer:

    I see HUGE value in the accordion as it appears on the original moo.fx page (http://moofx.mad4milk.net/) they key differentiator being the ability to control the tabs with the use of labels in the URL. This is accomplished via the url hash function–that much I know–and I use it with everything.

    I just don’t know enough about what I’m doing to be able to rewrite that part of it for 1.2.

    And I’m of course hoping that you can help. Of course.

    Please let me know if I overstep…I just really appreciated and am refreshed by a guy who a) knows what he’s doing b) is willing to share his knowledge and c) isn’t *exactly* a mootooler, so there isn’t the superiority stuff going on.

    Any reply greatly appreciated.

  13. David,

    Thank you for replying so quickly to my cry for help! :) I appreciate it!

    I had previously tried both Moo 1.1 or Moo 1.2. Neither worked. I have set things to run Moo 1.2 for now however to remove one variable.

    I don’t understand what you mean by the “wrapper” being missing from the accordion. Isn’t the wrapper the div statement with ‘ id=”accordion” ‘?
    I did include that encapsulating div in my test run.

    I also looked at the example from mootools.net; I don’t see how what I did differs from that example either.

    I even dumbed things down so much that all I had were toggler divs, followed by element divs, with simple text as their innerhtml. IE still failed to work.

    I am really feeling lost, but still not losing hope :)

  14. RS Justin

    PS

    And then he bent the rules. Realized that I only needed the functionality on page refresh, and if I was refresing the page, I could pass a GET variable via PHP, and if I could pass a GET, then I could feed the ‘display’ option in the Accordion function and voila. My ‘Tags’ tab or whatever it is, stays open if the user posted from there. Or whatever.

    I still blame this fertile and friendly environment for the breakthrough, however. So there.

    I’d still be very interested in seeing a 1.2 recretion of the accordion on the moo.fx site…if only for comparison and edification. There are some really cool but subtle things going on there (fades in the bg color changes, the aforementioned hash thing, etc) but of course, play at your own risk.

    But feel free to call in the dogs on that beer. :)

  15. David,

    You’re probably not going to believe this, but this was the problem:

    I had the above (without quotes) in the line above my doctype declaration. It is supposed to be a comment, eh? I’d copied my doctype from some source years ago and had blindly used the above immediately followed by the DTD. I have never had an issue until now.

    My implementation of the Moo accordion was fine, except for that odd glitch.

    I started testing by stripping out everything and building up the accordion related files line by line, adding my “faulty” code until things ended up breaking. The above was the culprit. Go figure.

    So, I am feeling a lot better, with one tiny exception-

    I cannot get the accordion to not display any element content in both IE and FF when I enter in the ” alwaysHide: true, ” as an option in the script.

    Anyway, I appreciate your attention in this. If you want to look at my second try, please look here-

    http://portal2web.biz/php/mootools_accordion_base

    Thanks again.

    -Joe Levin

  16. Och, sorry. The commenter nixed the line of code-

    !– saved from url=(0013)about:internet —

    (the above within LT and GT symbols).

  17. @Joseph: Scandalous!

  18. I agree. Scandalous.

    Any idea why the alwaysHide option is not working in either FF or IE?

    TIA,

    -Joe Levin

  19. Sorry….one more question-

    The scrollbars appear even though there is no reason for them to do so.

    Any suggestions?

    TIA again!

    -Joe Levin

  20. @Joseph: I don’t see scrollbars. Fixed, I take it.

  21. David,

    The scrollbars in question are in the main browser window.

    I’m not as interested in this issue as to why I cannot hide the elements on startup since using the alwaysHide option is not working in either FF or IE.

    Any ideas?

    -Joe Levin

  22. @Joseph: Taking a look at your source, it looks like you have a lot of hacks in there. Try removing some of those. If worse comes to worse, you can use CSS to remove the scrollbars.

  23. David,

    I don’t know what you mean by a lot of hacks. I count 1-

    //this script fixes the IE bug that won’t allow proper text selection. Script must be placed immediately before the ending body tag.
    document.body.style.height = document.documentElement.scrollHeight+’px’;

    Anyway, removal of this IE ‘hack’ doesn’t alter the scrollbar issue.

    I am still curious if you know anything about the alwaysHide option not working.

    Thanks again!

    -Joe Levin

  24. David,

    It seems that the alwaysHide option does not fire at all (has no effect).
    Perhaps it is a bug? I am not sure where I read it but I think Moo 1.3 is supposed to have this fixed.

    I figured out that what does seem to work is if you give the “show” option a value other than the range of elements in the accordion. I set show equal to -1 and it works swimmingly.

    I ended up solving most of the scrollbar issues with very little CSS. I only have a problem in IE6 (no horiz. scrollbar if requird) and Safari (no scrollbars at all), which I still have to work on.

    Take care!

    -Joe Levin

  25. David,

    OK, I think I’ve been at this long enough. I was able to get hover effects to work in all browsers via use of mootools (without hovering firing when the cursor is on the currently selected toggler), so I am very pleased. I want to say thank-you for hosting this tutorial and for your well of patience; I would have had a whole heck of a lot of trouble figuring out how to work with the accordion as an intro to MT if not for you!

    Here is my final try:
    http://portal2web.biz/php/mootools_accordion_base/

    Thanks again, and take care!

    -Joe Levin

  26. @Joseph: You’re welcome!

  27. Art

    Certainly a nice example of the accordion functionality, and easy to implement. However the usage of the word ‘toggler’ is somewhat misleading to me. What would I need to do to have them close upon click?

  28. @Art: To allow your accordion to have all items closed, you’d set the “alwaysHide” to true.

  29. Art

    @david Thanks for the info, I didn’t have an alwaysHide even specified, I created blank ones at the top and gave them a style=”display:none;” so nothing would be open on initial page load, this with the combination of the show: X works much better!

  30. Ryan

    Great tutorial. Can you make the accordion close when you click the toggler of a currently opened segment? Thanks in advance-

  31. Something isn’t working for me as well, but I think the problem is me not knowing which modules to download from Mootools. I clicked the “Accordian” one, and also chose the DomRead under ‘Utilities.’ Is that the right way to go about downloading the correct Mootools file? I had found a site that would break down which you needed when you gave it a .js file, but I have lost the address, I think that would be useful right now.

  32. Well, I’ve confirmed that my problem is as I described above, because I included every module (is that the right term, function, class?) in a Mootools download, and uploaded the huge .js file, and it works. So now to narrow down to the minimal ones I need… any tips? Thanks for the tutorial, and moreover, the awesome Mootools resources. =)

  33. Ben, I think the two you have to select in addition to Accordion are Window.DomReady and Element.Selector (which in turn selects Element.Filters as well).

  34. Mark

    Great tutorial, thank you!

    I have one question, is it possible to set one of the other sections to be open rather than the first one?

  35. Mark, put this in the JS declaration that you have in between your tags:

    display: 1,

    Where 1 would actually be the second section, because the counting starts at 0.

  36. Mark

    Great, thx very much, works like a charm :-)

  37. smartwork

    David,

    I am using the same and working fine, and i am adding image in toggler instead of text like this

    and its coming fine, i am using separate css class for image1.

    My question is How do i can change different image on this two status
    onActive: and onBackground: Do you have any idea?

  38. @smartwork: I’ve not heard of that being done before — you may need to hack the original class. I’d recommend checking out the official MooTools documentation first though.

  39. @smartwork: I’ve set up something like that here: http://www.relinc.net/new_design It both opens the accordion based on what link you came from, as well as applies an active image to the clickable region of the accordion, as well as has a hover state. The only thing I haven’t figured out yet (and not sure that I will), is how to get the active state to appear just when you open one section of the accordion; you have to change pages for the active state to change. Contact me via my site and I can help you if you’d like.

  40. smartwork, another method I used is to set the image as a background sprite in CSS. Then on the onActive and onBackground use something like this:

    For onActive:

    toggler.setStyle('background-position', '0px -55px');

    For onBackground:

    toggler.setStyle('background-position', '0px -33px');

    In my case, the background image is an arrow icon that points to the right by default. Then when you activate a particular item is points down to act as simple digdown menu tree.

  41. smartwork

    @Rick F: Thank you, its a really nice idea, i have used like this

    toggler.setStyle('background-image','url(/images/img1.gif)');
    

    i have used two image, because one with top curved corner, another one is just plain. I will try to change like your code with one single image.

  42. Thanks David

    Been searching for an easy way to do this with simple explanations

    Just 1 question though, what are the necessary components when downloading mootools?

    I want to keep the page as lean as possible.

  43. @Frankk: When you click on the “Accordion” checkbox on the MooTools download screen, it will also check the other modules you will need. You will also, however, need the “DomReady” class.

  44. Max

    Im having no scrollbars at all on safari (mac), what could be?
    On a pc, safari open the accordion and scroll very well as other browsers do, even on my iphone the accordion expands ok, why no scrollbars if needed on mac?

  45. Hey there-
    I’m absolutely frustrated with FF.
    My accordions are restricted in how high the content can go. For one of the sections I’ve used “oveflow:auto;” and in Safari this works fine – the scrollbar doesn’t show until opened. In FF, of course, it is shown and ugly.

    Any and all help would be appreciated!!!!!!
    http://www.portfolio.thecorkboard.org/projects/index.html
    ~Kyle~

  46. Katrina

    I am having problems with my accordion in IE, and was wondering if anyone had a fix –
    It shows all toggles expanded. I have found comments on many blogs about the issue, but haven’t found a fix yet. ( Also I am actually still using mootools 1.11 )

    I know this is an old post, but I appreciate any help

  47. @Katrina: Always easier to help when you provide a URL. :)

  48. Katrina-

    I just had this issue and found that my at the very top of the page were interferring with the accordion (weird, huh?). I moved the comments to the very bottom, outside of and it works fine now.

  49. @Paul
    I find a mix between padding and margin will “kill” the whitespace appropriately. See what I’ve done below for an example. It just depends on the height of your tab, too.

    .toggler {
    	background-image: url(../images/accordion_tab.png);
    	background-repeat: no-repeat;
    	width: 307px;
    	height: 38px;
    	padding-top: 10px;
    	margin-bottom: -20px;
    }
    
    .element {
    	margin-top: 10px;
    	margin-bottom: -10px;
    	width: 300px;
    }
  50. Katrina

    Unfortunately it can only be on my local drive right now. That being said it’s a rather long string of code and I noticed that people don’t generally paste their code on here.

    I don’t have any comments in the html right now

    Another issue I have come across is correctly using cookies to remember the state of the accordion – Several sites list “easy” solutions but I haven’t been successful in getting it to work for me. Generally when I try it expands all of the toggles, disabling the accordion.

    Thanks so much guys,
    Been snooping around on your site for awhile and love the tutorials!

  51. Matt

    David, while I didn’t make it here looking how to do the accordian script, I did come here for help with getting background images to swap and I wanted to thank you for opening a forum in which comments like Rick F’s can be found with such a stupid simple solution! Thanks to both of you!!

    I haven’t gotten too into my next issue, but has anyone figured out how to get the element to close after clicking on it?

    Thanks again! I wish I had found this sooner!

  52. Is there any way to get the accordion sections to expand when you hover over the elements that you would normally click on? I would think this would be documented somewhere, but I haven’t been able to find anything on the ‘net about it. Maybe I’m looking for the wrong thing, but any help would be appreciated.

  53. @Ben: I think you may need to hack the Accordion class. I bet it’s as easy as switching something to “mouseenter” instead of “click.”

  54. @bccarloso:

    I use this for my non-commercial web design for the roll over effect:
    http://creativepony.com/journal/scripts/autoaccordion/

    I would suggest pitching in something if you are making money off your project. The author quickly answers questions, if you have any.

  55. Jan

    Thanks for an excellent tutorial. But I would like to know if there is any way to add anchores to the elements of the accordion. In my case I have more text in the elements than can be display on one page. So when I have scrolled down to the next element in the accordion and clicks on it, the contents of that new element starts out of sight and I have to scroll up to get to the start of the new element. It would be nice if there was a way to add an anchor so that clicking on a element allways went to the start of that element.

  56. Tom

    Is there any particular way the divs have to be arranged to make this work?

  57. @Tom: You’ll need to arrange the DIVs from top to bottom, the way you would like them ordered in the accordion.

  58. Denny

    how do i select certain content on load based on the GET variable ?

    Thanks

  59. Paul

    Hi, Great Tutorial which I have working.

    One problem with it though. Is there any way to stop the hidden DIVS / Sections showing for a split second as the page loads in IE7.

    FF is fine and does not do this.

    This happens on the tutorial demo as well as the page I have created.

    Any help, much appreciated.

    Paul

  60. Paul

    Ok I think I have fixed it.

    Please let me know if there is a better way to do this.

    I added the following to the CSS.

    accordion {overflow: hidden;}

    .element { height: 0px; overflow: hidden;}

    This stops all the content showing for a split second in IE7.

    Hope this helps someone else.

  61. @Paul,

    I ran into the same problem. The way I did it was set all the Accordion element divs to style=”display: none;” and in my Accordion script I added this at the bottom:

    $$('#accordion .element').setStyle('display', '');
    

    Which goes through all the elements and sets display to visible (as the Accordion initializes). Yours is a much simpler way of doing it. The issue with both is if the user has Javascript disabled the items won’t appear.

    To counter that you could put an inline style class or CSS include below the Accordion init code and have it undo the CSS you applied. But that’s if you’re anal about non-js people having a good experience on your site. Plus it’ll make your page code a little uglier.

  62. Asep Sumardi

    thanks for tutorial David,
    but i have a little problem with doctype.
    if i’m use HTML 4.0 doctype, closed accordion element will have 100% height of element on IE7.
    else if i’m use XHTML 1.0 Strict doctype, accordion working perfectly.
    any idea to fix closed element height on IE7 without XHTML doctype ?

  63. Mariano

    Hi,

    Okay, so I’m giving mootools a shot for the first time and I think I’ve actually got it working the way I want it to be. However, I have the “element” set up with with a border, and the bottom (and top) of the element are being cropped whenever I toggle the element to display. If I de-activate javascript, the element appears correctly, so I don’t think it’s my CSS that’s the problem.

    Here’s the test page if you’d like to see it:

    http://testing.visitkeyport.com/accordion_test_page

    I’ve stripped it pretty bare, but am still seeing the problem.

    Thanks for any advice you can offer!

  64. @Mariano: Interesting. I generally don’t see users trying to separate the items from each other. I bet you can take the border off of the toggler, place a div in between the items with a top border, and keep the visual line there the whole time. I’ve done it before. Unfortunately, the site hasn’t launched yet so I can’t point you to it.

  65. Mariano

    Seems to work…thanks for the advice David!

  66. Hi!

    I also have an accordion in my website ( http://www.etconsultors.com ) and I’m very surprised of the power of this library, very nice effects can be realized with it.

    In fact I have a mixture of two effects that I believe that it has stayed well.

    I hope that you like this.

    Greetings.

    PD. If you want a tutorial of a vertical accordion, visit our blog : http://blog.etconsultors.com

    PD2. Sorry for my bad english :)

  67. Hi David,
    You know, I love how you presented the tutorial, but I would like to add something.
    The accordion tabs could have some slick effects (multiple ones). Active panel will have a style, default/collapsed/hidden panel will have a different one, and the hover effect of course, check it here in my website

    I thought it might be nice to share.

  68. Al

    David. This works well. I’ve been looking for this. Thanks so much. One question though, is there anyway to default hide the first element in the accordian?

  69. @Al: You could probably “display:none;” it.

  70. print("<div id="accordion">
    <div class="paneHead">Fold all</div>
    <div style="display:none;">
    <div class="contents"></div>
    </div>
    <div class="paneHead">Rod Stewart</div>
    <div class="contents">
        <div style="padding:5px;">
        <img src="http://davidwalsh.name/dw-content/accordion/every-picture.jpg" class="image" />
        <p>Roderick "Rod" David Stewart, CBE (born January 10, 1945), is a singer and songwriter born and raised in London, England...</p>
        </div>        
    </div>
    <div class="paneHead">Oasis</div>
    <div class="contents">
        <div style="padding:5px;">
        <img src="http://davidwalsh.name/dw-content/accordion/oasis.jpg" class="image" />
        <p>Oasis are an English rock band that formed in Manchester in 1991. The group was formed by Liam Gallagher (lead vocals), Paul Arthurs (guitar)...</p>
        </div>        
    </div>
    ");
    

    That works perfectly, I think!

  71. rachael

    David:

    Thanks a bunch.

    I’m trying to include a vertical scrollbar for each accordion div, to which I have set the fixedHeight to 100px. I have added the overflow:auto property to the .toggler style. However, no-go on a default scrollbar.

    Ultimately I’d like the scrollbar to be a mootools-based custom job a’la: http://greengeckodesign.com/projects/mooscroll/examples/mooscroll-example.htm.

    I’ve searched for another mootools accordion example doing this, but cannot find one. Any ideas from the group? David, any ideas?

    Thanks – Rachael

  72. Al

    I set display to a non existent element. This keeps the first element hidden. Probably an inelegant fix but I really don’t want to fool with it anymore today.

  73. Erick

    Why is there no resource on the web that has true “vertical accordion”, where the elements move sideways instead of up and down?

  74. Hi David,
    I’m going to completely relook my website and i’m planning to use your brillant code. A question : is there any way to open the items with the ‘mouse hover’ instead of the ‘click’ event ?

  75. spk

    Hi David,
    thanx for sharing!
    I’m having troubles with IE7 combining mootools scripts.
    At the adress http://www.spookdesign.fr , for the print section ( using another mootools effect : Fx.scroll) the content won’t appear smoothly. Can’t seem to find an answer to this bug, heeeeeeeelp (of course, no problem with FF).
    Thx :)

  76. @spk: That’s quirky as hell. I’ve never seen anything like that. I have no clue where to start to fix that.

  77. spk

    well thanx anyway for having taken a look :)
    Look what happens when I turn off the opacity otion “opacity:false” :
    http://www.spookdesign.fr/2
    The content stays always visible…
    hummmm, strange. I wonder how come no one has encountered this problem…

  78. Davey

    This is a really great tutorial and script — I love how simple and versitile it is.

    One quick question — say I want 2 of the accordian items opened. I can’t seem to get that working (only 1). How can you edit show: to return 2 or more open by default?

    alwaysHide: false,
    show: 2,

    (i tried show: 2 5, – 2, 5,) etc, nothing worked :(

  79. @Davey: I don’t believe that’s possible. Anyone else seen this done with Moo?

  80. Davey

    I’m curious if anyone has got this working on all browsers with flash content embedded inside the accordion. I experience a problem in Firefox (2, 3) where the content doesn’t remain hidden when the accordion tab it corresponds to it closed. So it turns into a pretty heinous mess.

  81. Jared

    Hello,

    I am very thankful for finding this tutorial so thank you David for your effort. I was wondering if anyone knows how to toggle the classes between an open panel and a closed panel so that when the page loads the background of the initial open panel is a different color than the closed ones and then when you click to open a closed panel the background color switches to the new open panel.

    A working example of this in action can be found at http://www.chinainstitute.org

    Is there a relative simple way to implement this?

    Thank you in advanced

    Jared

  82. Great tutorial! I started with your example, in a site for the swedish comedian Håkan Berg (or rather, for one of his characters). Still a work in progress, but I think it will become quite nice.

  83. i want to use two different sets of accordions on one page. Do you know how to do this? Every way i try i either one of the two is broken, or both work in conjunction.

  84. @cesar: You’re using different class names for the second accordion, right? And instantiating another accordion, right?

  85. thanks David. I figured it out later in the day, but it was as your suggestion is.

  86. Christophe

    is there a way to display all the content in the accordeon when printing the page?
    Would be great if someone could help me with this

    .toggler, .element, .element p, .toggler h3 { border-top: medium none; border-bottom: medium none; overflow: hidden; padding-top: 0px; padding-bottom: 0px; visibility: visible; opacity: 1; height: 180px; }

    in css with media=”print” doenst seem to do it. ( overuled by js written styles? )

    any ideas?

  87. Hello,

    I have a page that has a large amount of content in each .element. When I click the next toggler it causes the scrollbars to come in which is fine. However, it flashes like crazy and in safari the images inside of .element move outside of the div. Any idea if there is a fix for this?

  88. David

    Firstly, thanks for the great tutorial. I’m currently trying to get my head around learning mootools, but could do with a few pointers.

    I’m trying to add more than one style to the ‘active’ and ‘background’ state, so that I can have the text change to red and have a background position change when the ‘toggler’ element is clicked. Any help would be greatly appreciated :)

  89. Hi, this is a great tutorial, I’m using it for a new project now, but I’m also looking for a way to change the color of the link and backgroundimage when an item is clicked. (see David above) Now the background image only shows on rollover. Any ideas?
    Thanks!

  90. Hi,

    just a quick note to answer the question (several) above. If you want to start your accordion will all element closed then add the following two parameters: alwaysHide: true, display: -1

    The second is a bit of a hack – it defines the element to be first opened (default = 0); obviously there is no element -1 (which is why it works), but it does work and does not throw and error.

    p.s. love the blog

  91. Greache

    I have it working fine in FF3 but in IE7 I get the headings for the slides but it won’t expand or open any of them … not even the first one … any ideas?

  92. Charley

    David,

    Regarding your answer to Brian on 4-17-08:

    @Brian: You’ll need to set “alwaysHide” to true and set “show” equal to a number higher than the number of togglers you have.

    I found “alwaysHide” in the mootools.js file and set it to false.

    However for “show” I’m not sure where I’m supposed to change that in the mootools.js file.

    Basically I’m trying to setup the accordion so that all of the tabs are closed by default.

    Thanks,

    Charley

    • This is how I got it to work. After a bit of a blip with ie7 and ie8 (well no surprise there!)

      window.addEvent('domready', function() {
      	
      	//create our Accordion instance
      	var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
      		opacity: false, alwaysHide:true, display:11,
      		onActive: function(toggler, element){
      			toggler.setStyle('color', '#8DCFF4');
      		},
      		onBackground: function(toggler, element){
      			toggler.setStyle('color', '#E3EEF0');
      		}
      
      	});
      
  93. Tal

    Thanks for the tutorial. Things like this are very helpful while learning javascript. This is probably a fundamental type question but why doesn’t this script work externally. Does it need to be modified in some way. If I cut the following from my html file

    window.addEvent('domready', function() { 
            var accordion = new Accordion($$('.tab'),$$('.stretcher'), {
                opacity: 0,
                onActive: function(tab) { tab.setStyle('color', '#FF8000'); },
                onBackground: function(tab) { tab.setStyle('color', '#666'); }
            });
        });
    

    and paste into a new file accordion.js file and add

    <script type="text/javascript" src="accordion.js"></script>
    

    It doesn’t work.

  94. Tal

    Disregard that. I have something else screwed up.

  95. Nick

    Hi all,

    Quick question for the mootools Gurus. I’m desparately wanting to add an “expand all” button to my accordion, that expands all of the elements at once. Any ideas?

    Also, anyone else had padding problems when putting the toggler into a TD cell in IE7?

  96. Nick

    Also, I’m looking to add a small background image to the toggler that goes from a plus sign when collapsed, to a minus sign when expanded. I plan on adding it via the stylesheet, but I’m not quite sure how to manipulate the javascript to get it to change the background image when the toggler is in expanded mode…

  97. Nick

    Update, Figured out both the background image and ie7 td cell problems.

    But I’m still desparately wanting to add an “expand all” button to my accordion, that expands all of the elements at once. Any ideas?

  98. Jonathan bursac

    I seen a few people asking but I cant find the answer,

    sliding side to side rather than up and down?

    I seen it on a spanish guys website, couldn’t decipher the code.

    thanks

  99. James

    Love this. Great Job.

  100. Hi,
    I’ve implemented the accordion in a calendar, if you click a date the accordion with events show up, but the accordion doesn’t work.
    Clicking the date calls a javascript function, and within this function a string with htmlcode for the accordion is generated and shows up in the accordion div

     evnt5="<h4 class='toggler'>Titel2</h4><div class='element'><p>Dit gebeurt er vandaag 2</p></div><h4 class='toggler'>Titel3</h4><div class='element'><p>Dit gebeurt er vandaag</p></div>";
    
    function showevent(){ 
               evnt=eval(evnt5); 
               mydiv=document.getElementById('accordion'); 
               mydiv.innerHTML=evnt;
    }
    
    <div id='accordion'></div>
    

    It works fine if I don’t use the function, but it seems that the accordion needs to be reloaded after the function is executed or something, does anyone know how I can do that?
    Here’s the site:
    http://www.bonbonjournuit.be/nl/caltest

  101. Greetings, David!

    Tremendous thanks for posting this accordion script, it integrated nicely to a project I have in the works. I have read through all of the above posts, and googled extensively, but just can’t seem to find a way to alter the initial BG color of the bars. I can easily modify the hover color, and text on both, both no luck changing the current light gray to something else I need for this site project.

    In the latest post, I checked Ruben’s link and he did a great job with his, actually using ‘non’, I believe, as the BG color. That would work well for me, too.

    Any help one can provide would be stellar.

    Gracious thanks again! :)

  102. Hi Derek, this is my accordion:

    in the javascript:

    var accordion = new Accordion($$('.toggler'),$$('.element'), { 
            display: 15,
            alwaysHide: true,  
            opacity: 0,
            onBackground: function(toggler) { toggler.setStyle('color', '#000000');}   
        });
    

    css:

    .toggler  {
        cursor:pointer;
        font-weight:bold;
        color:#000;
        margin: 0;
        padding:5px;
        font-size:15px;
        font-family: Georgia, "Times New Roman", Times, serif;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #000000;
    }
    .toggler:hover     {
        background:url(../images/bkglinks.png) no-repeat right bottom;
        border-bottom-width: 1px;
        border-bottom-style: dotted;
        border-bottom-color: #000000;
    }    
    .element     { 
        padding:0 5px; 
    }
    

    For the hover background image, I took a png-image with transparent background.

  103. Derek

    Thanks, Ruben!

    I had viewed your source prior to your post, and still couldn’t get it to clear out. However, it was my bad, as I was modifying the coding within the page for that bg parameter, and not the external .css file. Doh! Problem solved now… thanks again.

  104. thanks man, Your script helped me to arrive at a better solution :). Am working on mootools and going to convert my site entirely using mootools.

  105. Your blog really helps, but I have a question with this accordion. Instead of using text and background changes, how can I use image rollover with active, hover, and current? Could you give me an example?

    many thanks.

    Erik

  106. Greetings – nice demo and examples. I would like to have accordion not close up a section when the user clicks on an element link withing a section. I am using the widget to implement a side bar navigation capability and it would be better if after clicking on an element link and displaying the related page the section remained open until the user expands different section – see http://www.sitmaacademy.com for example.

    Cheers and thanks.

    bc

  107. Hello, this is a nice accordion, but I want to know if it is possible make link to a specefic level of it – for ex. Oasis. So I would be able to href to it.
    Thanks for any answers.
    Jan

  108. @handz: You definitely could. You’d add a “click” event to your link that did something like accordion.open(2) //open the third item

  109. Thank you for a very quick answer David, Im a very weak in JS:( could you please show me how it should look like?

  110. lori

    Sorry if this is obvious but can you tell me where to download moo1.2.js?
    Thanks, the effect looks neat, hope to make it work.

  111. Hi David, great site, i love it. I’ve make an accordion page following your demo. My problem is that
    i want trigger the accordion clicking on a series of link so i wrote this code:

    window.addEvent('domready',function(){
    var myaccordion = new Accordion($$('h3.toggler'),$$('.regioni'));                                                                        
    $('clickme').addEvent('click', myaccordion.display('1'));
    });
    

    Where click me is the id of an a tag.
    It doesn’t work i get this message from firebug:

    condition.call is not a function

    i don’t understand how to solve it.

  112. Resolved:

    $('clickme').addEvent('click', function() {myaccordion.display(1);} );
    
  113. yuxell

    Hi,

    how i make more than one on one page?

  114. Hello,

    I’d like to know if it’s possible to make a link on another page that would trigger a specific part of the accordion. Couldn’t manage to do it according to your answer to handz

    Blockquote You definitely could. You’d add a “click” event to your link that did something like accordion.open(2) //open the third item

    Here’s my link : articles de presse

    Thx

  115. I could not manage it either. :(

  116. I found out that motools team made this with mootools 1.1 : http://moofx.mad4milk.net/. When linking http://moofx.mad4milk.net/#downloads you get directly to the download part of the accordion. Unfortunately I couldn’t get it to work on my mootools 1.2 accordion. I’m too noobie and I believe there’s a syntax problem in my code that I can’t resolve.. Could someone please give me a little more direction?

    Here is my js code :

     window.addEvent('domready', function() {
    
        var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
            opacity: false,
            alwaysHide: true,
            onActive: function(toggler, element){
                toggler.addClass('activePanel');
            },
            onBackground: function(toggler, element){
                toggler.removeClass('activePanel');
            }
        });
    
            //supposed to enable opening the accordion section relative to the url
    
            var found = 0;
            $$('h3.toggler a').each(function(link, i){
                if (window.location.hash.test(link.hash)) found = i;
            });
            myAccordion.display(found);
    });
    

    I would like to be able to link the same way to the differents sections of my accordion (ie : http://www.maeght.com/news/presse/#gasio opening the gasiorowski section instead of the default one)

    Thank you!

  117. jeff

    I have a accordian that is working but I was wanting to try and put a accordian inside this accordian. Like a nested accordian. Anyone have any suggestions on how to do this?

    Thanks.

  118. Hey David – Great work! I am looking to implement this as the navigation on my portfolio site, but would like to have it function so that in addition to starting with all the menus closed as the default, clicking on a header can both open AND close the content. In other words, you can get back to the default closed state easily. Is this possible?

  119. Hello,

    I know absolutely nothing about JavaScript, but I have managed to install scripts in the past when needed by carefully following directions. I am in the process of redesigning my site, and I first installed SmoothGallery http://smoothgallery.jondesign.net/ to creating a rotating feature story area.

    Since it was based on mootools, I thought I would leverage than platform and use this script to make a simple accordion area next to the main area to contain movie reviews — but I can’t get the script to work. If I put it in the head before the SmoothGallery script — neither works. If I put this script lower on the page, the gallery works, but this still doesn’t. Any help?

  120. I’m not good on Javascript but i want to learn more about it, i’m working on this page link text i’m using Accordion, but it won’t work, any idea? thanks

  121. Keith Wolf

    Thanks… Problem though…

    I have a page that uses AJAX to load a script that lists rows from a database, one column is shown as the header of each accordion element, and when you click it the accordion reveals the rest of the info from that database row. When viewing the script directly it works just fine, but since the script is being inserted into the page using AJAX the accordion doesn’t work, it just shows all the content as if the JavaScript wasn’t working.

    Any ideas on how to get the accordion to work within an AJAX box? I have this issue with other scripts too but it’s never been critical until now.

    Thanks,

    Keith

  122. Keith Wolf

    @ myself

    to clarify on my last post I am using typical AJAX functions to load the data, not mootools, i’m trying to get them to integrate without using moo for all ajax. if that helps.

  123. Hi,

    Thank you for this.

    I am currently researching various accordions for Vizion3 before I start the coding. I would like to know if it’s possible to nest Mootool’s Sliding Tabs inside one of the accordion’s panels, and nest the jQuery Agile Carousel inside another panel within the same accordion? Also, is it possible to make this accordion a vertical one?

    Sorry if they are ‘noob’ questions, I’m very new to Javascript.

  124. tom

    I’m pulling my hairs our and can’t figure what’s injecting the style into the ‘element’ ?

    print("<div class="element" style="border-top: medium none; border-bottom: medium none; overflow: hidden; padding-top: 0px; padding-bottom: 0px; height: 210px;">
    ");
    

    I don’t see it in your JS?

    anyone knows?

  125. Hello,
    nice tool.
    I’am using the newest mootools-1.2.2-core-nc_uc.js library. Why it doensn’t work anymore?
    If i use Davids version: 1.2.0 it works fine.
    any idea?

  126. Anyone got any ideas how to make the active pane`s title dissapear? (Toggler)
    I have been working along these lines but it always screws up the js file….

    //create our Accordion instance
    var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
        opacity: true,
        onActive: function(toggler, element){
            toggler.setStyle('color', '#41464D' 'display', 'none');
        },
        onBackground: function(toggler, element){
            toggler.setStyle('color', '#528CE0');
    

    I have also tried the following in the active toggler:

        onActive: function(toggler, element){
            toggler.setStyle('color', '#41464D' 'opacity', '0%);
    

    i am not exaclty a JS expert so any suggestions would be welcome!

    You can see my accordian at the homepage of http://www.snowsh.com in the search box. We use it to switch between search modes.

  127. Scripter

    Hey, for some reason when i use this accordion, it won’t work properly in Internet Explorer. But it works fine and great in Firefox. When i open it in IE all of the panels are already open, and if you click one of the headers (toggler) it just jumps up then slides back down. Can anyone help me out with this please?!

    Thanks!

  128. sirp

    can anyone tell me if it is possible to not see the entire accordion contents briefly before its loaded?

  129. sirp

    ignore above, ive seen the CSS solution further up, and applied that…it is an annoying bug in IE though

  130. AJ

    The accordion doesn’t work properly for me in IE, unless I include the strict doctype in the file.

    Hope that helps anyone else with the same problem.

  131. Hey David, this is a great tutorial, easy as can be, but I’m having an small issue:

    In Safari 4 (for Mac and for iPod) and IE 8 the first pane of the accordion, the one that starts open, actually starts half-open. To get it fully open I have to click some of the other togglers and then click the firts toggler again.

    Using the inspector on Safari, I can see that the height of that pane is 94px and it comes from in-line styling but I don’t see such styling either on the CSS nor the moo-tools file.

    I tried adding some additional in-line styling but this, of course, hasn’t worked.

    Thanks and keep on goingo with this work!

  132. Eduardo

    Hello,

    Thanks for this info. Jut one question:
    I’d would like to use this accordion effect in one page I’m building. But the text must come from a database. I mean, the accordion will be used to display some “upcoming events” which will be updated each week. How do I insert php code to display records on each section of the accordion?

    Thanks

    Eduardo

  133. HELP!!

    I made a webpage with the great accordion effect!
    But now i want some parts of the menu expanded (fold out) for a specific current page.

    Could somebody telle me how i can achieve that:
    http://www.burobengel.nl/fs/index.html

    Thanksss…

  134. HELP!

    I made a webpage with the great accordion effect!
    Now i want a specific part of the menu to expand (fold out) for a current page.

    Anybody has a clue? :
    http://www.burobengel.nl/fs/index.html

    Thanksss….

  135. Thankyou !
    It’s heplful

  136. David

    Am I right in saying that Mootools 1.2.4.2 has done something odd to the Accordion effect? I’ve updated my site with the new Mootools release this morning, and have discovered that it doesn’t appear to honour the fixed height property.

    It’s odd, it drops down to the required height, but the second it’s finished dropping down, it cuts back to where the content finishes.

    The JS looks like this:

    var accordion = new Accordion($$('.toggler'),$$('.services-element'), {
    	opacity: 0.3,
    	onActive: function(toggler) { toggler.setStyle('color', '#f30'); },
    	onBackground: function(toggler) { toggler.setStyle('color', '#000'); },
    	height: true,
    	width: false,
    	HeightToAuto: true,
    	fixedHeight: 260
    });
    

    Are they working on this or is my code no longer correct?

  137. Michal

    How to make two sets of accordians working seperately?

  138. Mark

    Hi I’m a newbe to all this but should it work on Firefox and Safari…?! In my case it doesn’t… can anybody help me out here?

    Thanks

    Mark

  139. Mark

    Does anybody know how I can change the color of the toggler when a mouse hovers over it?

    I cant get it done with css.. .toggler:hover works fine for changing the background color but not for the text inside the toggler class

    In the script the 2 lines give color to the active and background elements. Do I need to add something here?

    onActive: function(toggler) { toggler.setStyle('color', '#FF6600'); },
    onBackground: function(toggler) { toggler.setStyle('color', '#3D3D3F'); }
    
  140. @Mark: You can do this with pure CSS — no need for JS.

  141. Mark

    @David Walsh: Hmmm, nope… Must be doing something wrong here because the fontcolor doesn’t change when I try to do it with css

  142. Testing.

  143. Mat

    Hi, do you think it’s possible to reinitialize an accordion ? I explain : we use a menu bar with a set of buttons, and each button is suppose to reload the content of an accordion placed in the same page (without reloading the page of course). Thanks for your help !

  144. Stuart McCoy

    I’m using the mootools accordion to create a tabbed navigation element. I went with the accordion instead of a dedicated tab plug-in because of some UI choices the accordion offered over the tabbed UI. Most notable was the ability to turn off all the panels and still have the panel slide open instead of pop open instantly. One issue I do have, however, is the accordion assumes you want to have the panels slide on/off and I’d simply like to have them fade in/out when switching from one to the next. If there a way to override the standard accordion functionality so they fade in/out? Would this affect the way the initial panel opens?

  145. Aaron

    Great tutorial!

    Is there a way to open up multiple items in this accordion? or is it only possible to open 1 at a time?

  146. Hi David,
    Thanks for this great script. I believe someone mentioned before that the script won’t work if You use latest mootools release – 1.2.4. Any ideas why? Will be grateful for any help

    • I can’t provide information without knowing what error you’re getting.

  147. ahem...

    Nice work Dave. When clicking on each toggle that has a LOT of content inside, the screen does not keep it’s focus on the top of the next one that is clicked (I’m referring to the h3 heading). Instead it Zoooms past and next thing you know you’re in the middle of the article rather than at the beginning, so you have to scroll up.. How can the focus remain on the headings that are clicked?

    Thanks man.

  148. Hi There!
    Nice effect, but it does not work on my page. I use your code exactly (also copy’n’paste from you demo site) but it is not working!
    It looks like tehre is no effect, it shows all the content…

    Thanks, kurt

  149. Kurt

    Hi There!!
    Nice effect, but it does not work on my page. I use your code exactly (also copy’n’paste from you demo site) but it is not working!
    It looks like there is no effect, it shows all the content.

    Thanks, kurt

  150. Protidien

    Hello !

    The actual syntax for the class accordion seems to be :

    Fx.Accordion($('container'),$$('.toggler'),$$('.element'), {options}) ;
  151. Protidien

    Sorry for the first post, I sent before I finished typing.
    The second is the “right” one.

  152. Thanks for the great direction. One thing I’m trying to figure out is how to have an expanded element close if the link is clicked a second time. So, first click opens element and second click on the same link closes that element. How do I toggle the element open state open and closed?

    Thanks …

  153. thanks alot ur articles are really VERY VERY USEFUL
    THANKS ONCE AGAIN

  154. Hey there, great script, was wondering how I could close the active div by clicking the header?

  155. Dean Mortimer

    I’ve just been trying to get this to work with Mootools 1.3 and i’m getting some weird results. essentially when the H3 header text contains a space that particular toggle doesn’t work. So ‘The Beatles’ doesn’t work, although ‘Oasis’ does. Does anybody know if Dave’s example/demo works in 1.3? From what I have seen so far the event listener (click) doesn’t seem to get associated with the toggle when there is a space in the header text…

    • Dean Mortimer

      Update: I was trying to get this to work under Joomla 1.6 but that seems to be part of the problem (probably). When I created a very simple test using the latest Mootools + More without Joomla everything works as expected. Now to look into what is happening within Joomla 1.6 environment.

  156. kharmer

    Can anyone demonstrate how I would go about adding the ability for the page to load with the panel expanded relevant to an anchor string?

    I found some examples but they’re quite old and dont use Fx.Accordion!

    Best regards,
    K…

  157. kharmer
  158. gatsu811

    Hi! First I’m new in webdesign and editing, so be easy with me please! xD

    I’m italian, and i’m doin’ my first site with RapidWeaver 3.6 on MacOsx Tiger.
    I’m using a free theme (dirty3) with deepin’ custom element.

    Ok, the problem is simple as it get… I wanna use a hover-type accordion, and i was really affascinated of your demo on this blog… The problem is that i cant do the same…xD.

    I have understand that accordion the style.css, the index.php (or whenever is the page in question, my site is all in php), and a javascript (in this case, mootool.accordion.js)…

    On the first try i edited the Javascript (text type) in the page itself : rapidweaver put it on the bottom of the page, just next the page. Only later i realize the modify concerne the js file itself, the mootool.accordion.js in this case, where it declare the var accordion…

    Correct me if i’m wrong, i’m going with tentative to get this one!

    Now… I try to edit the mootool.accordion.js itself (i use textmate on macosx), but the code
    appear compilated to me: RW put the plugin in the “file” folder automaticatly, when i go online via http://FTP... So, how can i put this damned hover effect on my accordion? Where i’m wrong?

    Thanks in advice, hope i’m not too borin’ for you xD

    Gatsu

  159. gatsu811

    //

    This is the javascript inside the page itself… I’m thinking about download mootools.1.2.3.js and edit that one instead, but i dunno if it’ll work with my rapidweaver pages….

    In this case, i can add the Accordion code in mot.1.2.3 with the fireEvent click string, and give it a try…but it’s a complicate solution to me!

  160. Hi David, I followed your tutorial but the first toggler of the accordion isn’t working properly. Only after I toggle one of the other togglers the first one comes to life.
    Can you help me out please?
    note: I transformed the h3 of the example to div, does that have anything to do?

  161. With the rise of CSS3 and transitions etc., I’d like to control the accordion effects using pure CSS.

    Is it possible to add an active class to the active element as well as the toggler, so that I can do this? Cheers.

  162. Ramon Ramirez

    Hi,

    I’m trying to get the accordion working, but for some reason(I’m sure is something I’m doing)I can’t get it to work.

    I’m teaching my self how to use javascript/Jquery with books bought at a book store, and just now became familiar with mootools.

    could you please direct me to a site where I could read on how to use mootools?

    Thank you!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!