Grow your CSS skills. Land your dream job.

Last updated on:

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

Comments

  1. w1sh
    Permalink to comment#

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

    • Great share, however both demos function the same (clicking a new panel closes the previous). I believe once of the demos should function with the ability to open multiple panels at once.

  2. Thomas
    Permalink to comment#

    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
    Permalink to comment#

    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;
    
    	});
    });
    • steve
      Permalink to comment#

      use divs like:

      .accordion {margin: 50px; position : relative; }

      .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;
      } }

      $(function(){
      (function($) {
      var allPanels = $(‘.dd’).hide();
      $(‘.a’).click(function() {
      allPanels.slideUp();
      $(this).parent().next().slideDown();
      return false;
      });
      })(jQuery);
      });

  4. drizzy
    Permalink to comment#

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

  5. Is there a demo of this anywhere?

  6. Drizzy
    Permalink to comment#

    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
    Permalink to comment#

    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
    Permalink to comment#

    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. Kai
    Permalink to comment#

    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
      Permalink to comment#

      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
    Permalink to comment#

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

    Fabrice

    • Permalink to comment#

      position : relative; on the definition list itself would also do the trick and you that way you don’t need the extra div : )

  13. dan
    Permalink to comment#

    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. Permalink to comment#

    It solved my problem.
    Thanks a lot.
    Keep rocking…

  15. Permalink to comment#

    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>

    • Permalink to comment#

      Hey Ricardo,
      good tip. I’m by *no* means a developer and am just learning this stuff.

      How would you use the span?

      <dt><span>\"How do you choose the coffee?\".</span></dt>

      or

      <dt><span class="spanclass">\"How do you choose the coffee?\".</span></dt>

      And then swap

      $('.accordion > dt > a').click(function() {

      for

      $('.accordion > dt > span').click(function() {

      This is being used on maydaycoffee.com.au for FAQs.

  17. Ruana
    Permalink to comment#

    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
    Permalink to comment#

    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
    Permalink to comment#

    Ooops … hope this works :-/

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

    • Paul
      Permalink to comment#

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

  20. Permalink to comment#

    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
    Permalink to comment#

    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
      Permalink to comment#

      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. png
    Permalink to comment#

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

  25. Xirc
    Permalink to comment#

    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. Permalink to comment#

    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. Permalink to comment#

    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.

  32. Permalink to comment#

    Great script..

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

  33. Bacca
    Permalink to comment#

    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

  35. Davey

    @Josh and @Bacca – You can fix the bounce open and closed with this:

    (function($) {
    
      var allPanels = $(‘.accordion > dd’).hide();
    
      $(‘.accordion > dt > a’).click(function() {
        allPanels.slideUp();
        if($(this).parent().next().is(‘:hidden’)) {
          $(this).parent().next().slideDown();
        }
        return false;
      });
    
    })(jQuery);​
    
    • Greg
      Permalink to comment#

      Almost similar with your’s solution, this works for me and i submit it as an alternative solution:

      var allPanels = $('.accordion > dd').hide();
      
      $('.accordion > dt > a').click(function()
      {
          allPanels.slideUp();
      
          if($(this).parent().next().css('display')=='none')
          {
              $(this).parent().next().slideDown();
          }
          return false;
      });
      
  36. Bacca

    Hi Davey,

    Thanks for taking time to look at this, unfortunately I tried this solution and it was unsuccessful .

    When the page loads all the dds are open and clicking on the links in the dts does nothing?

    Any ideas??

  37. Hey Bacca,

    If you copied and pasted from my previous comment, the formatting creates an improper ” ‘ ” character. I forked the previous demo on jsfiddle here:

    http://jsfiddle.net/8MXAu/

    Try that. I tested it on jsfiddle and it was fine. This would also assume that you are using the same HTML and CSS as the example.

    • Chris
      Permalink to comment#

      Thanks Davey, that worked great and I am using different css than Chris. I changed the scss to old format and changed from there to fit my theme. Thnx again!

    • JYoho
      Permalink to comment#

      Thanks Davey! That worked great and solved the bounce issue :)

  38. Jon

    Davey-

    I just came across this demo. The original works fine except the “jump” your fix breaks completely. Any idea why that may be the case?

  39. Hey Jon,

    Check out the jsfiddle link here:

    http://jsfiddle.net/8MXAu/

    If you copied the fix from my previous comment, it does break because of an invalid ‘ character. Is that how you tested it?

    • Bacca

      Thanks Davey,

      I had noticed the invalid character after I copied it, thought I had changed them all but must have missed one.

      Anyway keyed in code from scratch (which i should have done in the first place) and it works perfectly, many thanks.

    • faris
      Permalink to comment#

      thanks alot mate. your fix works. cheers

  40. This snippet helped me immensely. Thank you for sharing.

  41. max
    Permalink to comment#

    Not a jquery expert,

    need to have several accordions in 6 columns any ideas how to do this? my js fiddle http://jsfiddle.net/FL7q3/

  42. This i great!
    How do I only show one panel at a time?

  43. Tiffany Israel
    Permalink to comment#

    Any idea how to add a window.scrollTo? I’m not super proficient in Javascript/jQuery expert so I’m not sure where to put it.

  44. Permalink to comment#

    I tried this to allow for accordion tabs (dt) to be collapsible once opened:

    $(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;
           });
    });
  45. Chuck Ezuma
    Permalink to comment#

    This is one of the better accordion demonstrations. Nice and clean.

  46. MP
    Permalink to comment#

    Nice tutorial…

    Has anyone incorporated a [+] and [-] into this accordion, either by way of Javascript or images?

    That would be really really cool if someone did…!

    • Krish
      Permalink to comment#

      Hi MP,

      I did my accordion with Plus and Minus signs, but there is one small bug in it. When I click the icons are jumping. Is there any solution for the icons jumping?

      Krish

  47. Permalink to comment#

    I could not get this working. Mainly as I am a n00b and didn’t know about swapping $ for jquery.
    Also a bit of jquery lightbox wizardry I am using caused a conflict.

    Here’s how it was fixed.

    I got my mate whom I use for dev (and who kicks butt) to fix this and we have this working on maydaycoffee.com.au.

    The jquery used is:

    <script src='http://code.jquery.com/jquery-latest.js'></script>
    								<script>
    								jQuery(document).ready(function()
    								{
    									var allPanels = jQuery('.accordion > dd').hide();
    									
    								    jQuery('.accordion > dt > a').click(function()
    								    {
    								        allPanels.slideUp();
    								        
    								        if(jQuery(this).parent().next().is(':hidden'))
    								        {
    								            jQuery(this).parent().next().slideDown();
    								        }
    								        return false;
    								    });
    								});
    </script>

    CSS is below. I converted from SCSS. Like I said, I am not a dev/designer so my syntax and probably semanticism SUCKS.

    .accordion dt, .accordion dd {
    		padding: 5px;
          border: 1px solid #815611;
          border-bottom: 0; 
          font-family: inherit;
    	  font-size: 0.9em;
    
          &:last-of-type {
            border-bottom: 1px solid black; 
    		}
    }
    
    .accordion dt a, .accordion dd a
      {
            display: block;
            color: inherit;
            text-decoration: none;
            font-weight: bold;
          }
    
    .accordion dd {
    
         border-top: 0; 
         font-size: inherit;
         &:last-of-type {
           border-top: 1px solid #815611;
           position: relative;
           top: -1px;
    	}
    }
    
    .accordion dt{
    color: #A90329;
      margin-top: 1em;
    }
    • quiet0ne
      Permalink to comment#

      Awesome, this worked perfectly. Thank you for sharing that solution!

  48. Awesome !!! cool code for making a very simple jquery accordion.

  49. Oimy

    god bless you, Chris!

  50. Hi, just a quick question. I’m trying to change the selectors to ul and li instead of dd dl and so on. But it wont seem to work. Any ideas?

    Thanks in advance
    /Jeppe

  51. Hello agian,

    forget about my previous question. I solved it by actually closing all elements :)

    How ever I have another qestion. If one wants for the clicked panel to scroll to top och into view. How would I do that out from your code?

    Thanks!
    /Jeppe

  52. Annabelle du Blogovoyage
    Permalink to comment#

    Hi,

    For those who are looking for a French accordion tutorial, here is a great one : http://netmacom.fr/blog/webdesign/creer-un-menu-accordeon-avec-jquery.html

  53. Brian
    Permalink to comment#

    To get the first one to show (previous solution someone posted didn’t work).

    I did:

    var allPanels = $('.accordion > dd').hide().first().show();
    
  54. Brian
    Permalink to comment#

    Errr ignore the previous post, it breaks it.

    Just add this line below the var allPanels line:

    $('.accordion > dd').first().show();
    
  55. Ramesh Chowdarapally
    Permalink to comment#

    It can be used as fundamental, but not as advanced.

  56. Permalink to comment#

    My accordion version at his simplest. Style it as you wish. h3 can be replace by anything…

    JQuery (Javascript):
    $(document).ready(function() {
    $(‘[id^=aContent]‘).hide();
    $(‘[id^=aContent]‘).prev().click(function() {
    $(‘[id^=aContent]‘).hide(300);
    if ($(this).next().is(“:visible”))
    $(this).next().hide(300);
    else
    $(this).next().show(300);
    });
    });

    CSS:
    .aHeaders {/* Put the style for your accordeon headers here… */}
    .aContents {/* Put the style for your accordeon contents here… */}

    HTML:
    <h3 class=”aHeaders”><a href=”#aContent1″>Header 1</a></h3>
    <div class=”aContents” id=”aContent1″>
    Content1
    </div>
    <h3 class=”aHeaders”><a href=”#aContent2″>Header 2</a></h3>
    <div class=”aContents” id=”aContent2″>
    Content2
    </div>
    <h3 class=”aHeaders”><a href=”#aContent3″>Header 3</a></h3>
    <div class=”aContents” id=”aContent3″>
    Content3
    </div>

    Cheers!
    -Pierre-

  57. Permalink to comment#

    I edited Pierre’s snippit to allow the first element to be displayed on load.

    $(‘[id^=aContent]‘).hide();
    $(‘[id^=aContent]‘).first().show();
    $(‘[id^=aContent]‘).prev().click(function() {
    $(‘[id^=aContent]‘).hide(500);
    if ($(this).next().is(“:visible”)){
    $(this).next().hide(500);
    } else {
    $(this).next().show(500);
    }
    });

    Cheers

  58. Permalink to comment#

    @Kevin: if you want to open multiple dd elements at once, do this:

    $('.accordion > dt > a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
        $(this).parent().next().slideToggle();
        return false;
    });
    
  59. Brilliant — thanks Chris.

    I added an active class for the dt. Not a strong writer of jQuery so for anyone who might improve this, thank you in advance:

        (function($) {
          var allTriggers = $('.accordion > dt');
          var allPanels = $('.accordion > dd').hide();
          $('.accordion > dt').first().addClass('active');
          $('.accordion > dd').first().show();
          $('.accordion > dt > span.toggle').click(function() {
              $this = $(this);
              $target =  $this.parent().next();
              if(!$target.hasClass('active')){
                 allPanels.removeClass('active').slideUp();
                 $target.addClass('active').slideDown();
              }
              $trigger =  $this.parent();
              if(!$trigger.hasClass('active')){
                 allTriggers.removeClass('active');
                 $trigger.addClass('active');
              }
            return false;
          });
        })(jQuery);
    
  60. Permalink to comment#

    You can further simplify it by using JQuery “.accordion()” function. Since you do not have to do much except designing it using CSS. All you need is couple of elements inside a container and let the JQuery do the rest.
    Its that simple.

  61. Permalink to comment#

    Your tutorial has converted me into using SASS. Thank you!

  62. Permalink to comment#

    I got it working! Although there is one thing that isn’t working properly and I can’t seem to be able to fix it. When I click on a panel, the description opens but as it opens, the width is smaller. When it has finished loading, it bumps to its full-length. How do I fix this? http://michellecantin.ca/test/features/accordions/

  63. Cynthia
    Permalink to comment#

    Hi how do I build an accordion within an accordion? please help! thanks!

  64. Christopher
    Permalink to comment#

    Sweet, worked first time, I even managed to convert the css back to ‘normal’ on the first try. I am using this accordion for an FAQ section. For those who aren’t familiar with sass here is the css I used, it’s very much the same, but no-doubt someone has been cought out by that ‘&’:

        .accordion {
        margin: 30px;
        position: relative;
           }
            .accordion dt, .accordion dd{
                padding: 10px;
                border: 1px solid black;
                border-bottom: 0;
            }
            .accordion dt:last-of-type, .accordion dd:last-of-type {
                border-bottom: 1px solid black;
            }
        dt a, dd a {
            display: block;
            color: black;
            font-weight: bold;
        }
        dd {
            border-top: 0;
            font-size: 16px;
        }
            dd:last-of-type {
                border-top: 1px solid white;
                position: relative;
                top: -1px;
            }
    
  65. Michele
    Permalink to comment#

    Hi there,
    Can someone explain this line in the code for me?
    $(this).parent().next().slideDown();
    If (this) is referring to $(‘.accordion > dt > a’), then wouldn’t that line refer to the title of each panel and not the paragraph of text in the panel that needs to be displayed?

    I’m also unclear as to why this: (function($) { })(jQuery); needs to wrap the entire function in order to work.

    Thanks!

    • christopher
      Permalink to comment#

      ‘this’ always refers to the current object, to find out what it is use
      console.log( “what is this? ” + $(this).parent() );
      right before or right after the line you quoted, and then read the output from the console. I think in the accordion it is the parent of the clicked object > next sibling of that parent object. So the start of the next element that will ‘open’.

      Your second question is answered here
      stack overflow, answer by Vivin Paliath -scroll down for the answer

  66. Permalink to comment#

    to make it unclickable when open

    $j(‘.accordion > dt > a’).click(function() {
    allPanels.slideUp();
    if($j(this).parent().next().css(‘display’) != ‘block’){
    $j(this).parent().next().slideDown();
    return false;
    }
    });

  67. Josiah Nusbaum
    Permalink to comment#

    Does anyone know how to make it so that you can close the “open drawer”? I’m using this in a website for a class, and my teacher is taking away points because the “open drawer” won’t close.
    Thanks in advance for your help!

    • christopher
      Permalink to comment#

      If you mean that all of the accordion sections should be closed on start, you can do something like:
      var allPanels = $( '.accordion &gt; dd' ).hide();

      and that should hide all of the contents of anything with an .accordion class. To show only the first on load add after that line:
      $('.accordion &gt; dd').first().show();

  68. Cameron
    Permalink to comment#

    How would you add the plus minus sign to it?

    Thanks!

    • christopher
      Permalink to comment#

      Add a class to the element you want to add the +- icons to then use something akin to;
      css:
      .notselected{
      background: url(‘plusIcon.png) no-repeat;
      background-position{ 98% 50%; /* horiz, vert */
      }

      In the main js/jquery function:
      var allHeaders = $(‘h1.accHeader’).addClass(‘notselected’);
      $(allHeaders).first().removeClass(‘notselected’);

      Where h1.accHeader (in my code) is a clickable header (dt.a in the example)
      And then in your onclick function you will need to reverse it:

      allHeaders.addClass(‘notselected’);
      $(this).removeClass(‘notselected’);

  69. Great snippet, thank you. Has anyone tested this for mobile? Works great on the iPhone 5. I ask because this would be an excellent solution for mobile menus.

    Sam

  70. Alan Sutherland

    Thanks for this dude

  71. ashish
    Permalink to comment#

    It has some issues with pagination……it doesn’t work when you go to the next page using pagination.

  72. Michael
    Permalink to comment#

    I know this post is pretty old now, but I would sitll like to say thanks a lot for this write up, the comments are a gold mine as well.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".