How to expand collapse (toggle) div layer using jQuery

Pin It


collapse expand jquery In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1:

Include jQuery Library in head section of your html file.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Step 2:

Come up with your own html elements in body section. I chose div ‘layer1′ to be the main container where collapsible/expandable content would reside.

Next, class ‘heading’ is given to header while div ‘content’ holds the show hide layer for that heading

Like this:

<div class="layer1">
<p class="heading">Header-1 </p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p class="heading">Header-2</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p class="heading">Header-3</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
</div>

Step 3:

CSS: Now it totally depends on you to write css for your heading, div. Here’s my version of CSS for this example.

.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
 
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }

Step 4:

Again lets go to head section to add few more javascript codes.

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class msg_body
  jQuery(".heading").click(function()
  {
    jQuery(this).next(".content").slideToggle(500);
  });
});
</script>

Thats it!! Expandible-Collapsible panel is ready. You may like to view a DEMO.

73 total comments on this postSubmit yours
  1. Just what I as looking for on my wordpress blog. Worked perfectly! Many thanks for sharing.

    • You’re welcome. :)

      • Could you please tell me how to do expand collapse for nested divs and for n levels?

        • aa

      • Thank you ^^

  2. Great post. Thank you for the code.

  3. I love when I can take some code and paste it into an html file and it works right off. Then I can play with it to make it do what I need. I tried a few others and they didn’t work. Thanks for the simple and complete code.
    Colin

  4. Many thanks for the well written code. Yours is the first example of an expand/collapse div that actually worked with more than one div.

  5. One question, how would you make an expanded layer automatically close when the next layer is opened?

    • Also, a link at the bottom of the layer to close it would be useful on large single layers
      Thank-you

    • Hey Richard, this is done through the addClass() method:

      $(“.cell”).click(function() {
      var kid = $(this).children(“.cellExtra”);
      var dad = $(this).parent();
      var toggledKid = $(dad).find(‘.toggle’);

      $(toggledKid).hide().removeClass(‘toggle’);
      $(kid).addClass(“toggle”).show();
      });

      • Hello, I a bit new to this so could you pls explain where this code goes so that expanded layer automatically close when the next layer is opened?

        Thank you very much for your help.

      • Please elaborate on this more as I’m a bit confused on how to implement this (I’d like it to ‘slide closed’ when another one is clicked.

        Currently, I’m just adding the line
        jQuery(“.content”).hide();

        right above, jQuery(this).next(“.contentx”).slideToggle(500);

        and it works, but it’s not ‘appealing’ visually.

        Also, any chance you could explain how to make an ‘expand all’ button that would expand all ‘content’s with one click?

        Thank you!!!

      • Could you provide the syntax to match your specific code above? I tried changing .cell to .heading and .cellExtra to .content. Also are we supposed to create a new class called .toggle that is hidden? Thanks!

        • Chris, I think you need to make changes in HTML part too.

  6. how i toggle to up becoz right now its down… help me ahtsham.com

  7. I am using the words “show more” prior to toggling down. How would you have the words change to “show less” once the full content is shown? Thank you for the great script!

  8. So nice, clean and simple, thanks! My Worpdress sidebar is now full of exandable / collapsible content ares :D

  9. You are an absolute legend, im using text pattern for building my website and its taken me an age trying different codes to make this work with textpattern. yours has been the only one so far which works perfectly (bar the few adjustments) cheers man.

  10. Great post. Thank you for the help.

  11. Working great ..! Thanks a lot ..

  12. What i want is that when ever the header is clicked it displays the contents from the database.can we do that?combining php and jquery.so,will please help me.hope for positive response.

  13. the problem is solved.any way thanks for such a helpful post.

  14. I will use this in my new drupal site. Thank you for the code.

  15. thanks for your expand/collapse, it saved my time…

  16. Could you please tell me how to link to an anchor within the collapsed div that will make it expand? So, further up the page, I have some text with a link to #anchor – the anchor link is further down the page within the collapsed content. When somebody clicks the text link I want it to expand the collapsed content AND go to that spot. Can that be done?

    Otherwise – awesome, works really well :-)

    • Hi Alison – did you ever find a way of getting this functionality? I need to do the same thing – link to content inside one of the hidden divs from another page, but am very stuck! Thanks!!!

      Claire =^.^=

  17. Is there a way to save that state?

    ie, if someone expands the middle bar, refreshes the page, the middle bar will still be expanded?

  18. I’ve been trying out several show/toggle and this worked for me exactly how I want it and with minimal fuss. Thank you for sharing!

  19. Super i like it

  20. thank you

  21. This is a great post. I love how simple jQuery is.. very useful

  22. Thanks a WHOLE bunch! It works beautifully.

    I just haven’t a clue as to how you get the + and – on there?

  23. Wow! This was great!! I love how easy it was to do. I am just learning javascript, CSS, etc. and I was actually able to understand what each sections purpose was. :-) One small step closer to becoming a web designer! lol I am also curious how to do the + and – so they change when it is clicked. Thank you again!

  24. thanks ! it’s work right ! thanks !

  25. Hello there, do you know if it is possible to keep the toggle hide when the page is loading ? Because it suddenly appears and desapears on loading. Do you know a way to avoid this ?

    Thx in advance !

  26. Thanks a lot!!. It solve my problem.

  27. Thank you for the tutorial!

    twas’ of great help :)

  28. bravo, nice work, very easy to implement. how do you do the whole + or – next in the p class-header based on whether it is expanded or not?

  29. exactly what i needed. built this into a project in less than 10 minutes.

    brilliant!

  30. I have a little problem about collapsing div menu, I have this piece of jQuery:
    $(“.options”).slideUp();
    $(‘.menu_head’).toggle(function() {
    $(“.options”).slideUp();
    $(this).next(‘div’).slideDown();
    }, function() {
    $(this).next(‘div’).slideUp();
    });
    This is allow me to open one menu, and others will be hidden automatically, the prblem I face now is if click on element in the menu, the whole menu will be slide up, how I can fix this.

  31. If i need 2 (or more) divs of Content under the Heading which should be hide/shown? Thenks!

  32. this was very useful! thank you! I am just wondering if there’s a way to style the “active” .heading using css? for example, when i click on a heading, I want that heading to stand out from the other headings…. thanks for any help

  33. hi richards, great post. i have a pressing question though. how do i integrate this code seemlessly into my wordpress blog post? pls reply

  34. Danke für diesen Tipp! Hat auf Anhieb geklappt! Ich bin mit dieser Lösung sehr zufrieden!

    Wann klappt schon mal was auf Anhieb beim Webdesign? :)

    Liebe Grüße und Danke!

  35. Thanks for the wonderful tutorial.

    but I was trying to integerate this with my blogger.

    But it is not working there…..my blog just goes blank….
    Couldn’t figure out the reason..

    The moment I write $(“.content”).hide();

    IT breaks !!

    Can you please help?

  36. Thanks to my friend jashwant, who helped me figure out the problem while implementing this on blog.

    The problem was the the content class was already being used in my blog.

    I changed the name of the class and it worked.

  37. hi, it just worked fine :)……but then shows a scrolls bar , once it shrinks back…..i dont want that scroll bar….how to overcome ?this

    • I hear a simple “nudge” of the window will trigger them off. scroll up or down 1 px then back to nudge the screen and the scroll bar will disappear.

  38. I need to impliment facility to expand all and collapse all in above given example. so is any script which works here.p
    if possible then give me script.

    Thanks

  39. Hey, is it possible to add a second link at the top of the page that will expand the div?

  40. Works like a charm, happens to work even with the WordPress qTranslate plugin which itself shows/hides html. Yay!

  41. Nice
    and I would like to hear updates of jquery topics through mail

  42. THANNK YOU FINALLY I FOUND AN EASY WORKING TUTORIAL.

  43. Thanks you so much. It was really easy and simple! :)

  44. Thanks alot for this, was exactly what i was looking for.

  45. great ideas which is very helpful like me :)

  46. great, I love it, but on longer content (height) towards the bottom the smooth goes jerky and jumps to the end!

    How do you fix this? Any help email me :] :]

    • Got it, I set the width on the .content!

      (encase anyone else has the same problem)

      Great code!

  47. Thank you so much! It’s just what I was looking for.
    How do I disable the click when it has expanded?

  48. Great, just what I was looking for and so easy to implement!

  49. Works great! Thank you for this tutorial.

  50. Thanks i was searching the same thing

25 total pingbacks on this post
Submit your comment

Please enter your name

Your name is required

Please enter a valid email address

An email address is required

Please enter your message

Twitter

  • May 2, 2012 04:15

    10 Free WordPress Theme To Make You Forget About Premium Theme http://t.co/YRiLCiVa

  • March 2, 2012 17:16

    3 Helpful Tools to Test Cross Browser Compatibility of Webpage http://t.co/FY0jh8Dn

  • March 2, 2012 16:43

    3 Helpful Tools to Test Cross Browser Compatibility of Webpage http://t.co/QUlYKInf #IE #FF #Chrome #Testing #CrossBrowser

  • March 2, 2012 12:52

    Top 5 Plugins to Build Contact Form for WordPress http://t.co/PWyR08Iq #WordPress #Plugins #ContactForm

  • June 11, 2011 02:49

    CSS 3 Transitions http://bit.ly/m0pK3t

Design Gala © 2012 All Rights Reserved

Designed by 76miles

Powered by WordPress