Code Snippet

Home » Code Snippets » jQuery » Simple jQuery Accordion

Simple jQuery Accordion

jQuery

Make sure either to run on DOM ready or at the bottom of the page.

(function($) {

  var allPanels = $('.accordion > dd').hide();

  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });

})(jQuery);

HTML

<dl class="accordion">

<dt><a href="">Panel 1</a></dt>
<dd>Pellentesque fermentum dolor. Aliquam quam lectus, facilisis auctor, ultrices ut, elementum vulputate, nunc.</dd>

<dt><a href="">Panel 2</a></dt>
<dd>Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</dd>

<dt><a href="">Panel 3</a></dt>
<dd>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.</dd>

</dl>

SCSS

Sorry if you don't use SASS. Should be pretty easy to convert.

.accordion {
   margin: 50px;
   dt, dd {
      padding: 10px;
      border: 1px solid black;
      border-bottom: 0;
      &:last-of-type {
        border-bottom: 1px solid black;
      }
      a {
        display: block;
        color: black;
        font-weight: bold;
      }
   }
  dd {
     border-top: 0;
     font-size: 12px;
     &:last-of-type {
       border-top: 1px solid white;
       position: relative;
       top: -1px;
     }
  }
}

View Demo

Slightly more advanced, preventing closing of active panel:

View Demo

Subscribe to The Thread

  1. w1sh

    Thanks Chris. I was looking for a simple, lightweight alternative to all that jQueryUI jazz.

  2. Thomas

    This works well with just tags, but what if I have an image included with a tag? I added in some lines of code, but now when I click on a div, the images appear/disappear but no content ( tags) show up.

    Very odd……this is the code I used. Any help for someone learning Jquery would be appreciated greatly!

    $(document).ready(function() {

    $(‘#skills-services p:not(:first)’).hide();
    $(‘#skills-services img:not(:first)’).hide();

    $(‘#skills-services h3′).click(function(){

    $(‘#skills-services p’).slideUp();
    $(‘#skills-services img’).slideUp();
    $(this).next(“p”).slideToggle(“normal”)
    $(this).next(“img”).slideToggle(“normal”)
    return false;

    });
    });

  3. Thomas

    I tried altering this code block to include images, but now only the images appear/disappear and the content ( tags) are nowhere to be seen.

    Very odd, but here is the code I used. Any help would be greatly appreciated to someone new to Jquery.

    $(document).ready(function() {
    
    	$('#skills-services p:not(:first)').hide();
    	$('#skills-services img:not(:first)').hide();
    
    	$('#skills-services h3').click(function(){
    
    		$('#skills-services p').slideUp();
    		$('#skills-services img').slideUp();
     	    $(this).next("p").slideToggle("normal")
    		$(this).next("img").slideToggle("normal")
            return false;
    
    	});
    });
  4. drizzy

    whoa never mind.. I didn’t close the tag

  5. Is there a demo of this anywhere?

  6. Drizzy

    is it possible for it to collapse more into sub heading as well?

    So basically if you had a heading:

    i.e.

    > Major Attractions ‘you click that it drops down to’
    > CN Tower ‘and when you click that it drops down
    > ‘a short description of the CN tower’

    is something like that possible ?

  7. Rohan Merchant

    I made one to slide up the next one when you click the same one… I’m sure there’s a cleaner solution but I cant figure it out. If you do post back thanks.

    
    $.fn.equals = function(compareTo) {
            if (!compareTo || !compareTo.length || this.length!=compareTo.length)
    {
                    return false;
            }
            for (var i=0; i<this.length; i++) {
                    if (this[i]!==compareTo[i]) {
                            return false;
                    }
            }
            return true;
    } 
    
    $(document).ready(function($) {
    		var whichOne = $('#accordion');
           $('#accordion dd').hide();
           $('#accordion dt a').click(function(){
           		if(whichOne.equals($(this))){
           			$('#accordion dd').slideUp();
           			$(this).parent().next().next().next().slideDown();
             		whichOne = $(this).parent().next().next().next();
                }else{
    	            $('#accordion dd').slideUp();
    	            $(this).parent().next().slideDown();
    	            whichOne = $(this);
    
                }
    			return false;
           });
    });
  8. Patrick

    How can I use this with WordPress’ dynamic navigation?

  9. Thanks.
    This gives me some more ideas on accordion.

  10. Awesome! just what I was looking for!

  11. Hi, Thanks for the tutorial, just what iw as looking for.

    Just 1 quick question, how would i make the tabs collapsible, so that all can be closed?

    i have tried adding in ‘collapsible: true’ but to no avail.

    Thanks

    • Bert de Vries

      I did this:

      $(document).ready(function($) {
             $('#accordion dd').hide();
             $('#accordion dt a').click(function(){
                if ($(this).hasClass('selected')) {
                     $(this).removeClass('selected');
                     $(this).parent().next().slideUp();
                } else {
                     $('#accordion dt a').removeClass('selected');
                     $(this).addClass('selected');
                     $('#accordion dd').slideUp();
                     $(this).parent().next().slideDown();
                }
                return false;
             });
      });

      Works for me…

      Gr. Bert

  12. __fabrice

    Hi,
    To avoid the “jump” bug, just add : position : relative; on a parent div.

    Fabrice

  13. i came up with an even simpler solution:
    you don’t have to override the accordion click function because by calling accordion(“activate”, false) the all parts are closed (and hiding helps that this is not seen by the user). i also set collapsible to true… don’t know if thats necessary.

    $(document).ready(function($) {
    	// hide all content if the hash is null
    	if (window.location.hash == "") {
    		$("#accordion .content").hide();
    		$("#accordion").accordion("activate" , false);
    	}
    });
  14. It solved my problem.
    Thanks a lot.
    Keep rocking…

  15. Simple and effective!

  16. The best way to avoid page jumping is to not use dummy links (a href=”#” or a href=”") at all. a href’s have a lot of SEO weight so you may want to use them to actually link to other pages/sites, not to trigger behaviors.

    To trigger behaviors you can use any other HTML link, yes, it will work, all you’d have to do is add “cursor:pointer;” to your CSS file and that’s it. And yes, this works in IE6 too.

    So in Chris’s example above just replace:

    <a href=”"></a>

    with:

    <span></span>

  17. Ruana

    Hi,

    unfortunately the “jump” remains, at least in IE7, not matter whether one applies a position: relative; on a parent div or replaces the dummy links with real links or a spans – with which the indication that the lines are links is missing is not clear to the user. The headlines must unmistakable scream: Click me, I’m a link! to the users).

    If anyone could come up with a solution to get rid of that nasty jump (in IE7 too) and post it here I’d be very grateful.

    • The return false should prevent the jump // but you can also the following: adding an event to the click function and then immediately preventing the default behavior /

      function accordian(){

      $(‘.accordian dd’).hide();
      $(‘.accordian dt a’).click(function(event){ // <– add the event

      event.preventDefault(); // <— prevent the jump
      $('.accordian dt a').click(function(){

      $('.accordian dd').slideUp();
      $(this).parent().next().slideDown();

      });

      });

      }

  18. Paul

    Regarding the jump……

    If the container which is being animated ( the dd) has margin or padding this seems to greatly increase the jump.

    If you put your content inside a and put the padding on that instead of the , this seems to greatly reduce the jump.

    Text

  19. Paul

    Ooops … hope this works :-/

    &ltdd&rt&ltp&rtTEXT&lt/p&rt&lt/dd&rt

    • Paul

      No .. I’m obviously stupid :-/ Antway, just put the P inside the DD :-)

  20. I’ve been searching for a simple accordion script and this might just be the one. Others I’ve found are very convoluted but this one is nice and lightweight, thanks.

  21. Daryl

    Hey guys, this is great – on every browser except IE7.
    I have tried every hack out there to get it to work but it’s just not working. Any hints?

    • Daryl

      I apologise, after hours of lost sleep I tried a new attack. It turns out the IE7 I had installed on my mac (using Winebottler) wasn’t loading ANY javascript and couldn’t be modified.
      The script still works beautifully as intended.

  22. Nicole

    great article

    I using the following code

    $(document).ready(function() {

    /********************************************************************************************************************
    SIMPLE ACCORDIAN STYLE MENU FUNCTION
    ********************************************************************************************************************/
    $('div.accordionButton').mouseover {
    $('div.accordionContent > .acitem', this).show();
    $('div.accordionContent > .acitem', this).prev().addClass('active');
    $('div.accordionContent').slideUp('slow');
    $(this).next().slideDown('slow');

    });

    /********************************************************************************************************************
    CLOSES ALL DIVS ON PAGE LOAD
    ********************************************************************************************************************/
    $("div.accordionContent").hide();

    });

    now all the menu will closed at once, i want one menu should be open and remaining closed, how it can be achieved? or slow menu closing will also do.

  23. thank you for sharing…
    here an another link for another jquery accordion:
    http://www.bijusubhash.com/blog/create-a-simple-accordion-with-jquery-and-css

  24. would like to know if you are still answering any of the comments in this thread, simple jquery accordian
    thanks

  25. Xirc

    Great, simple, thanks!
    Could you help to support cookies and remember open &ltdt>?

  26. Hi there, is it possible to implement this menu with more than one dd tag? I understand it goes against definition lists… can I use li tags instead? Sorry I’m pretty new to jQuery, any help would be much appreciated. The list I’m trying to implement would have the structure:

    Projects
      - project1
    - project2
    etc
    

    Thanks guys!

  27. thank. gracias desde colombia. me sirve muchisimo.

  28. Thanks so much. Really clear article.

  29. Thanks for the tutorial, it really help me a lot.

  30. Im having a weird bug with this code as it is posted originally. If you click one of the menu items to expand it does expand but if you click the same menu item to close it, it bounces closed then open again.

    Does anyone know how to turn this bounce off?

  31. damn, i just spent an hour getting this to work but cant get rid of that annoying jump it does. read all these comments and still get the jump….ok back to the drawing board. there has to be something simpler out there.

    • Marz

      add position : relative; to .accordion class.. that fixes the jump

  32. Great script..

    Is there a way to get the first item in the accordion to be open on page load rather than hiding all?

    • var allPanels = $(‘.accordion > dd’).hide().slice(1).show();

  33. Bacca

    I’m having the same problem as Josh (01/26/2012)

    Does anyone know how to turn this bounce off?

    It would be nice to have the option to close the menu item you have just opened

  34. Hello !
    Thanks for posting this amazing tut, its really simple, I was just need to know, is that possible to make this accordion work dynamic, for example if am working on eCommerce website and i have more than one item is that possible while am scrolling the accordion open panel for the item name something like giving order to accordion panel. Any help.
    Sorry for my English. Thanks

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~