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.

[syntax_prettify linenums=””]
.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; }
[/syntax_prettify]

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.

136 replys to 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
      1. 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

        1. 1. First you have to put the “jquery-1.3.2.min.js” file downloaded from the internet in a library on your sharepoint.
          2. You have to create an aspx file (may be in notepad) and put on the 1st line the path to the js file:

          3. You add the div and paragraphs structure like in the article
          4. At the end of the aspx file you paste the java script from the article
          5. You uploade the aspx file on the sharepoint and make links to it from other pages :)

          1. script type=”text/javascript” src=”https://share.bla bla bla…/jquery-1.3.2.min.js”></script

            i removed the at the beginning and end of the line otherwise I cannot post it

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

  8. Pingback: Pieter Kubben
    1. 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();
      });

      1. 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.

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

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

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

  10. 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.

  11. Pingback: Nisha
  12. Pingback: Nisha
  13. Pingback: Maurizio Stasi
  14. 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.

  15. Pingback: Javascript News
  16. Pingback: M.B.Asfoor
  17. Pingback: Gabriel Feitosa
  18. Pingback: Gabriel Feitosa
  19. 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 :-)

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

  20. 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?

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

  22. Pingback: Joseph Twumasi
  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. 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 !

  25. Pingback: junichi_y
  26. 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?

  27. 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.

  28. 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

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

  30. 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?

  31. 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.

  32. 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

    1. 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.

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

  34. 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.

  35. 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?

  36. 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

  37. 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

  38. 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?

  39. 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”);
    });
    });

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

  41. 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 ?

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

    1. 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?

  43. 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

  44. 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?

  45. 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 .

  46. 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

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

    doug

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

  49. 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

  50. 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(‘[+]’);
    }
    });

    });

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

  52. 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

  53. Good morning

    I am a beginner zn programming with Bootstrap and I made ​​a FAQ.
    Until then, I met the collapse div hand.
    But now I want to do it using SQL queries.

    Can you help me, please.

Leave a Reply

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