How to expand collapse (toggle) div layer using jQuery

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.

129 Comments How to expand collapse (toggle) div layer using jQuery

  1. Pingback: WordPress Rocker

  2. Pingback: raulblon

  3. Pingback: Anish Lama

  4. Pingback: Design Gala

  5. Pingback: Design Gala

  6. Pingback: jQuery Tips

  7. Pingback: uberVU - social comments

      1. Monika

        Anish i can see that most People implement it into wordpress. How to do it with Ms sharepoint 2010. Any advise? I tried to implement the code through cwe but did not work… Thanks, monika

        Reply
  8. Colin Callahan

    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

    Reply
  9. Lenton

    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.

    Reply
  10. Pingback: Pieter Kubben

  11. Richard

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

    Reply
    1. Richard

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

      Reply
    2. tyler

      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();
      });

      Reply
      1. alan

        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.

        Reply
      2. James

        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!!!

        Reply
      3. Chris

        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!

        Reply
  12. Judie

    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!

    Reply
  13. Tim

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

    Reply
  14. Nathanael

    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.

    Reply
  15. Pingback: Nisha

  16. Pingback: Nisha

  17. Pingback: Maurizio Stasi

  18. sprajapati

    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.

    Reply
  19. Pingback: Razee » Blog Archive » How to Expand/collapse WordPress posts with jQuery

  20. Pingback: Javascript News

  21. Pingback: M.B.Asfoor

  22. Pingback: Gabriel Feitosa

  23. Pingback: Gabriel Feitosa

  24. Alison

    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 :-)

    Reply
    1. claire louise

      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 =^.^=

      Reply
  25. question

    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?

    Reply
  26. Seluna

    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!

    Reply
  27. Pingback: jQuery Toggle | Matthew Wehrly

  28. Pingback: shahriza khairudin

  29. Pingback: Joseph Twumasi

  30. JOe

    Thanks a WHOLE bunch! It works beautifully.

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

    Reply
  31. Lorelei

    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!

    Reply
  32. Paulo Henrique

    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 !

    Reply
  33. Pingback: jQuery toggle divs epantzar epantzar

  34. Pingback: junichi_y

  35. Pingback: Cộng đồng dịch đầu tiên tại Việt Nam | Blog | How to expand collapse (toggle) div layer using jQuery

  36. NTD

    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?

    Reply
  37. SIFE

    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.

    Reply
  38. Annika

    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

    Reply
  39. Pingback: how to expand collapse toggle div layer using jquery | SeekPHP.com

  40. Strichcode

    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!

    Reply
  41. Yogesh Gandhi

    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?

    Reply
  42. Yogesh Gandhi

    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.

    Reply
  43. jenny

    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

    Reply
    1. Mark

      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.

      Reply
  44. alex

    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 :] :]

    Reply
  45. Pingback: How to expand collapse (toggle) div layer using jQuery « Macphisto007′s Weblog

  46. breck

    If I use partial postbacks with this control, how do I re-initialize the control?

    I love it…until my user performs a partial postback (in this case, using ASP.NET updatepanel). After the partial postback, the control doesn’t work anymore.

    How do I re-initialize it? I’ve tried executing the same code after the postback…doesn’t work, either in FF or in IE.

    Thanks for any help.

    Reply
  47. Tom

    Hi,

    exactly what I was looking for – thank you!

    wondering if it would be simple to extend this so that only one layer is open in the same time – opening one layer is closing the other opened layer?

    and also: loading the content of the layer fist via ajax when expanding it?

    Reply
  48. Renée Picard

    Bonjour
    Comment mettre :
    closedSign: ‘[+]‘,
    openedSign: ‘[-]‘,

    I want to put a + and a – in jquery headind and i do not know how?
    Sorry for my bad english!

    Thank you
    RP

    Reply
  49. Nduh

    plz help, what if u r using ASP.NET master pages. when your menu is with a class and a body on the other page with , plz email me so that i’ll forward screen shots of u don’t understand

    Reply
  50. Pingback: Demo Resources 04.08 | Website Design One

  51. Super Coach

    Your page appeared first on Google when I searched for jQuery Expand Collapse div….

    It took only 5 mins for me to integrate it in my project

    No wonder why your post appears first ,….. it deserves….

    Thanks

    Reply
  52. Mark

    Anyone got any ideas of how to add a ‘close’ link within the content so the viewer doesn’t have to scroll to the top to close the header?

    Reply
  53. shantanu

    I need some modification in the script but could not do it as i am not so friendly with jquery

    When the page postback i want to maintain the state of the panels. Right now if i refresh the page all the panels are collapsed,

    i am using the below code

    $(document).ready(function () {
    $(“DIV.ContainerPanel > DIV.collapsePanelHeader > DIV.ArrowExpand”).toggle(
    function () {
    $(this).parent().next(“div.Content”).show(“slow”);
    $(this).attr(“class”, “ArrowClose”);
    },
    function () {
    $(this).parent().next(“div.Content”).hide(“slow”);
    $(this).attr(“class”, “ArrowExpand”);
    });
    });

    Reply
  54. Nils

    Very cool. Thanks for posting this. It’s one of the simpler methods of doing the accordion and it’s very flexible. Thanks again!

    Reply
  55. Abhijeet

    very good and easy demo, like having lunch in breakfast ;)

    i just want to ask how to store the value of the div which is openend during postback ?

    Reply
  56. Newb

    I have to click the header three times before it expands or collapses any idea why? Here is my code:
    $(document).ready(function () {
    $(“.msg_body”).hide();
    $(“.msg_head”).toggle(function () {
    $(this).next(“.msg_body”).slideDown(100);
    }, function () {
    $(this).next(“.msg_body”).slideUp(300);
    }, function () {
    $(this).next(“.msg_body_info”).slideDown(100);
    }, function () {
    $(this).next(“.msg_body_info”).slideUp(300);
    });
    $(this).(“.msg_body_info”).slideDown(100);
    });

    Reply
    1. Baz

      wanted to have one div drop down showing – so added this to head and created two more css class’ one for opencontent and one for openheading

      jQuery(document).ready(function() {
      jQuery(“.opencontent”).show();
      //toggle the componenet with class msg_body
      jQuery(“.openheading”).click(function()
      {
      jQuery(this).next(“.opencontent”).slideToggle(500);
      });
      });

      It works, but is this the correct way to do it?

      Reply
  57. Andy

    Brilliant tutorial with clear instructions. I’m a newbie to CSS and Javescript, but it only took me a few mins to put it in my page.

    Thanks

    Reply
  58. Mattew

    Hi! i find the tutorial and the demo very esplicative!
    I was trying the code in a (FF)GreaseMonkey project i’m working on, but i’m getting constantly an error message: “jQuery is not defined”.
    I get the same even after the add of .noConflict() method (just in case).
    Not sure why it’s not working on me.
    Any suggestions?

    Reply
  59. Munish Kumar Gumber

    Hi,

    I am also using jquary in Sharepoint. Its working fine,when i am using in Dreamwiver.
    But when i implement the same code on Sharepoint its generating some code or Id that i don’t know..like jquery1356717204441=”3″ ,jquery1356717204441=”7″ etc.If anybody have an idea about this.Please send me the the resolution on my email-id – munish.gumber.029@gmail.com .

    Reply
  60. Doug Lerner

    It works great. But I have one question. Is there a way for the .content to be hidden as the page is loading, perhaps with an inline style or something? On a large page with many .heading and .content elements all the .content elements are expanded until the document fully loads.

    Thanks,

    doug

    Reply
  61. Doug Lerner

    Nevermind. I just applied an inline style=”display:none;” for each of the .content elements and it worked fine.

    doug

    Reply
  62. Biro

    Thank you for the easy code. In an attempt to help, this mod will open the one clicked and close the one previously opened.
    jQuery(document).ready(function () {
    jQuery(“.content”).hide();
    //toggle the componenet with class msg_body
    jQuery(“.heading”).click(function () {
    jQuery(“.content”).hide(500);
    jQuery(this).next(“.content”).show(500);
    });

    Reply
  63. Amelia

    May I know how do you make the design of the Expand/Collapse look like the picture you provided? The one with the Arrow at the bottom left

    Reply
  64. Mathew

    Toggle with plus minus

    $(document).ready(function () {
    jQuery(“.content”).hide();
    //toggle the componenet with class msg_body
    $(“.heading”).click(function () {
    $(this).next(“.content”).slideToggle(500);
    var t = $(this).text();
    if (t.substring(0, 3) == ‘[+]‘) {
    $(this).children(‘span’).text(‘[-]‘);
    } else {
    $(this).children(‘span’).text(‘[+]‘);
    }
    });

    });

    Reply
  65. Frederik

    Just in case anyone else wants it to only have 1 open at the time, you can do it like this:

    $(document).ready(function() {
    $(“.content”).hide();
    $(“.heading”).click(function()
    {
    $(“.content”).slideUp(500)
    $(this).next(“.content”).slideToggle(500);
    });
    });

    Reply
  66. Monika

    Need some help. Managed to get to the stage with your tutorial where I have three nicely red heading with collapsed text below, when hoverning over Header 1 I see it as a link, buit would not hide. What am I doing wrong? I have implemented it in SharePoint 2010 via CWE

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>