Animated JavaScript Accordion V2

Javascript 70 responses so far

A new version of this script is available here.

This lightweight (1.16 KB) animated JavaScript accordion is an update to the original accordion script posted on April 18th. It is now smaller, faster, supports multiple instances and includes an active header class toggle. The markup is also improved through the use of definition lists and the CSS has been simplified as well.

To initialize an accordion use the following code:

var mySlider=new accordion.slider('mySlider');
mySlider.init('slider',0,'open');

You must create a new accordion object before initialization. The parameter taken by accordion.slider is the variable name used for the object. The object.init function takes 3 parameters: the id of the “dl”, the index of the initially expanded section (optional) and the class for the active header (optional).

This script has been tested in all major browsers and is available free of charge for both personal or commercial projects under the creative commons license. Community support is available here. Paid support is also available, contact me for details.

Click here for the demo.

Click here to download the source code.

Update 11/24/2008 – Updated logic to allow hover state when no sections are initially expanded. Consolidated some code to drop the weight by 15%.

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Scriptiny Editorial (see all)

  • It seems like a terrific update, congratz!

    I especially like the fact that it doesn’t break when a I go crazy with the mouse and click very fast every link. It proves that the script is well build. I find the demo very fluid also.

    Great job, indeed!
    Thanks for sharing with the rest of us.

  • Have you got my emails I sent few of them?

  • @Nemanja – I will look for them this evening and get back to you.

  • Pingback: Monday warm up | Ionut Staicu - Webdeveloper Blog()

  • Thanks Michael!

    I really need your help with this. I told you everything in the mail.

  • Pingback: Animated Accordion Script Without Any JS Framework | Creative VOI()

  • This is really cool. Thanks for sharing.

  • It is possible to have somekind of a timer that rotates throught the sliders if none selected ? It would be great for news or other kind of content display 🙂

  • Thanks, amazing… what you think about collapsible panel?

  • Haris

    How can I add a pic of mine next to my comments????????

  • The divs don’t appear to open their full height in Safari 3 on mac. . .

  • @César Couto – That would be fairly simple. Inside the init function set an interval to call a net function that iterates through all the items in the “this.arr” array and calls the process function. As part of the process function you would also have to determine if the function was called called via a header click or through the auto function, if by click then clear the interval. If others are interested in your customization I will put it together.

  • @Daniel Lopes – Obviously you could have a definition list with only one header and content section but there is a bit of overhead there that could be eliminated by stripping out certain parts of the script. I might add a separate script for this that has a few additional features. Thanks for the suggestion.

    @bobby marko – Thank you for the report. I will try and get access to a Mac to test. If you could send me a screenshot I would appreciate it.

  • Cool according.. Deserve to b book marked

  • Fred

    // More Compact version (1128 bytes)
    var accordion=function(){var
    T=10,S=10;function
    slider(n){this.Q=n;this.A=[];this.Z=”}
    slider.prototype.init=function(t,c,k){var
    a=document.getElementById(t), h=a.getElementsByTagName(‘dt’), s=a.getElementsByTagName(‘dd’),l=h.length,i;for(i=0;i<l;i++){var
    d=h[i];this.A[i]=d;d.onclick=new Function(this.Q+”.P(this)”);if(k!=null&&c==i){this.Z=d.className=k}}
    l=s.length;for(i=0;i<l;i++){var
    d=s[i];d.W=d.offsetHeight;if(c!=i){d.style.height=0;d.style.display=’none’}}}
    slider.prototype.P=function(d){var i,l=this.A.length;for(i=0;i<l;i++){var
    h=this.A[i],s=h.nextSibling;if(s.nodeType!=1){s=s.nextSibling}
    clearInterval(s.R);if(h==d&&s.style.display==’none’){s.style.display=”;U(s,1);h.className=this.Z}else
    if(s.style.display==”){U(s,-1);h.className=”}}}
    function U(c,f){c.R=setInterval(function(){V(c,f)},T)}
    function V(c,f){var
    h=c.offsetHeight,m=c.W,d=(f==1)?Math.ceil((m-h)/S):Math.ceil(h/S);c.style.height=h+(d*f)+’px’;c.style.opacity=h/m;c.style.filter=’alpha(opacity=’+h*100/m+’)’;if(f==1&&h>=m){clearInterval(c.R)}else
    if(f!=1&&h==1){c.style.display=’none’;clearInterval(c.R)}}
    return{slider:slider}}();

  • Unfortunaly my javascript knowledge is almost null. I’ll wait and see if more people are interrested in a rotating function. Thanks for the answer 🙂

  • Pingback: Webmaster Libre | Acordeón animado con javascript en sólo 1.3KB()

  • Thanks, amazing… what you think about a new collapsible panel?

  • Hello. I really like your accordeon. I would like to use it to publish my blog’s comment participation rules under my comment’s edit box in WordPress.

    I’m not a programmer or anything; just a blogger. ¿How do I install this in my blog?

    Thanx for your help.

  • Blix

    As always an amazing job! The best accordion I have seen to date.

    I’m definitly going to use this on the website for my volleyball team :-).

    Thanks!

  • Gyanendra

    Gr8 work!
    The source code would be more clear and easy to vary parameters if you name variables by generic names instead of alphabets.

  • Indeed, a very nice and streamlined code.
    Although I liked the use of DIVs in the old version better, you can’t use many XHTML tags inside a DL, like unordered list, or headers, etc.
    It works just fine if you are only using text though.
    I would also like to see a valid xhtml implementation, without the script calling inside the file.
    Cheers again for this little gem.

  • wow! thanks for this. its really usefull.

  • pw

    This works great and thanks for all your hard work.

    There is one fundamental problem though, and this is also true for the drop-down menu example – the image rollover does not work in IE. It might seem like a small issue but it is not. Because I’m a designer I notice it right away.

    This problem has not been formally addressed and really needs to be. Providing a fix for this example and the drop down menu would be ideal. Thanks again.

  • Richard Graves

    I’ve only just started with web design and I think it is amazing that everyone helps each other with coding. Thank you for your support. The info I have downloaded has made my site look far better.

    The Novice.

  • Pingback: Geek Links on jQuery, PHP, CSS, XHTML, Web Design, Fireworks, Flash | JasonCypret.com()

  • @Roderick – Thanks for the information, I had not considered the nesting issues. I will dig into it a bit and make any needed changes soon.

    @pw – It would not work in IE6 as it did not support the pseudo hover class but IE7+ does. You could overcome the issue by changing the class via JavaScript if your require it.

  • Definitivamente Exelente el Apunto Gracias thank you!!!

  • It would also be interesting to know how to target each parent node to the ul-li-ul’s in order to get rid of the necessity for the class “parent” on the parent A-tag. 🙂 Some “if” and “for” to check?

  • Hi! Thanks for such a wonderful lightweight script! But when I put it inside my web-site where there are a lot of tables it seemed not working. I’ve tested a lot and made simple example of working and not working situations. It’s all about where to put the script code. Inside the table or outside. But I can’t understand why it matters. Can you help me to explain it? ‘Cuz in this small pieace of code I could figure it out how to make it work but for my large and complicated website I still don’t know how to make it (I’ve tried to put a code in many places).

    So, this is a working code:

    http://www.2step.ru/test/working.html

    And this one doesn’t work:

    http://www.2step.ru/test/notworking.html

    I hope you can easy understand my problem and give me some hints how to avoid it.

    Thanks in advance!

  • I forgot to mention that in Firefox both my examples are working just fine. I have a problem with IE7.

  • Collapsed section with the class for the active header.

    If I use this code:

    var slider1=new accordion.slider(“slider1”);
    slider1.init(“slider1″,0,”open”);

    All my headers got the class “open”. But if I want to not open on load
    any section, how can I make headers use that class ‘open’?

    These tries don’t help:

    slider1.init(“slider1″,”open”);
    slider1.init(“slider1″,,”open”);
    slider1.init(“slider1″,””,”open”);
    slider1.init(“slider1″,”12345″,”open”);

    So how can I make it happen? Thanks in advance for your help…

  • John

    I have a strange problem. It works fine in all browsers except for one strange thing, in FF and Safari all of the web page is now left aligned instead of centred, it’s fine in IE7 and Opera. Any ideas about this?
    One thing I noticed is that if I remove the CSS * {margin:0; padding:0} then FF and Opera do centre the page, however the expanded text is shifted to the right by 40 pixels and the text is cut-off and no border shows on the right.

    Hope this makes sense.

  • Is it possible to include images in place of or as wel as text? So for example, instead of the word “Instructions” on the example, could I have it display an image? When I try to do it it just shows a picture missing icon. Anyone help?

  • I love this script! However, I will continue to use the older version because I need to have it set up with divs. Great job though!

  • Pingback: Animated JavaScript Accordion V2 - Web Development Blog | Enjoy News, Feeds & Share All Your Favorite Media Online With The Rest Of the World… Video, TV, Shows, Music, Audio, Pictures, Images, Games, News, Feeds, Links, www.CLHMedia.com()

  • Matt

    I got in implemented fine on my site. Thanks for the great code.

    Only thing is that for some reason, when i go to click each header to recollapse the box, it won’t collapse back. I copied the code exactly. Any ideas? I’m using Firefox on a Mac.

  • Another great piece of JavaScript. Thanks!

  • Stucca

    Hello, i need that accordion work with event mouseover, but i have problem with this, no work fin.

    d.onmouseover=new Function(this.nm+”.process(this)”);

    And i need that the div no close if this is open.

    cant you help me?
    thanks.

  • Hi!

    Great Code! The accordion works beautifully…Just one problem: The IE seems to have difficulties with the font in the collapsed section. (Even in the Demo version.) I would like to use Verdana or Georgia but IE shows some other font. I encoded everything in UTF-8. It’s fine in Safari or Firefox. What’s wrong? Who can help?

  • Fabian

    OK- Well I found the problem… IE seems to have difficulties with opacity:

    c.style.opacity=h/m; c.style.filter=’alpha(opacity=’+h*100/m+’)’;

    But I quite like that feature! Is there any way I can get it to function in IE?

  • Ashish

    Hi,
    Michael .. this script is amazing …. thanx for sharing .. but i need some help … i have mailed you and have explained my problem .. just check out….
    thanx regards .. ASHISH !!!

  • Vitor

    Hi,
    great work!!!
    But i’m with a problem, i want that the accordian show all them closed when i open the page.
    I tried to change the “open” to “close” and “closed” but didn’t work :/
    They only appear closed if i change the number to a higher then the accordian that i have, but with that, the down arrow and up arrow dont change.
    How can i fix this?

    Regards

  • If anyone could help: I have an issue where everything in the accordion is pushed to the right and I can’t seem to find the CSS rule that is making it do this. I may have the width setup incorrectly on the accordion itself but not sure. Problem can be found at http://www.bakersgas.com/index2.html, on the right hand side.

  • This is a great javascript. Thanks for posting!

  • Excellent piece of art, unfortunately doesnt work with ajax.
    Meaning that when i call a page with this feature doesnt work.
    pity!

  • With ajax it would work if it had an “onclick” function to put on the header….

  • Saran

    I would like to appreciate the efforts of the developer for giving realistic animation effect with minimum code

  • Yoshihiro

    This is very nice! I’m trying to modify this to a vertical nested accordion, but I’m having a lot of trouble understanding the jscript code. Any help?

  • Pingback: Web Vertical Menu and Horisontal Menu Which I like()

  • Cam

    good stuff, i coded out my own but was bulky and a lil slow. this one is light weight and works well.

  • Okay, I got the thing to work on mouseover and I twiddled with the styling.
    Is there a way to make it not collapse an open item?

    Excellent scripts, by the way. I think it may not be far when I have a site featuring all your scripts 🙂

  • okay, found it.
    change line 14 from
    <blockquote>if(h==d&&s.style.display==’none’){s.style.display=”; su(s,1);}</blockquote>
    to
    <blockquote>if(h==d){s.style.display=”; su(s,1);}</blockquote>

  • Kristin

    If this could go horizontally you would be my hero 🙂

  • Satya

    Hi there, awesome job, thank you very much, but seem nae working with IE 7, open at start, so i closed it, and wont open (expand) again, any help would be appreciated….thanks again…oh but it would working perfectly with FF…:)

  • las6

    a Nice addition to anyone’s library of goodie javascript scripts, but not all is well with it. The use of Definition list puts constraints on the content and doesn’t behave very well in all circumstances.

    It might be my code, but the javascript calculated height for the elements is off – it’s always less than what it should be, though the amount varies from block to block. Thing is, I have disabled most of the CSS affecting the list and validated the page using tiny and tried all sorts of tricks with firebug that seem to fix the problem (but if I make the same changes to the CSS, the problem is still there)

    so does anyone here have any idea where to start when trying to get the elements to the correct size when opened?

  • las6

    ah, figured it out finally. Had to put the initialization at the very end of the page, otherwise the layout wouldn’t render properly leading to erroneous sizes in the sliding elements…

  • blue

    Can anyone tell me how to use this to make nested accordions?
    Great script! If i could get it to have multiple levels, 3 or 4 ideally it would be a lifesaver.
    Thanks.

  • Mike

    Thanks a ton! Best accordion on the web. Great code, working fantastically! Uber Kudos.

  • Hans

    Just what I needed for a collapsable menu structure. (CMS and backstage)

    Thanks!!!