Tutorials

Latest Word » Tutorials » Simple Toggle with CSS & jQuery
Simple Toggle with CSS & jQuery

Simple Toggle with CSS & jQuery

Tags: ,

I know there are a lot of toggle tutorials out there already, but when I was learning the basics of jQuery and the toggle effect, I had a hard time finding resources on how to switch the “open” and “close” graphic state.

After reading a few tutorials and mix and matching techniques I was able to achieve this effect, but wanted to share it with those who experienced the same frustration that I had gone through.

Easy Toggle Tutorial - jQuery

Step1. Wireframe & Style

We start out with an h2 tag with a link as the “trigger” for our effect. Below our h2, we will have our container where we hold the content.
Note that we nest the container within another div. One of the main reasons I decided to do this was to prevent the padding from easing up and down during its action. Take a look here for a bad example of a toggle.

HTML

<h2 class="trigger"><a href="#">Toggle Header</a></h2>
<div class="toggle_container">
	<div class="block">
		<h3>Content Header</h3>
		<!--Content-->
	</div>
</div>

CSS

h2.trigger {
	padding: 0 0 0 50px;
	margin: 0 0 5px 0;
	background: url(h2_trigger_a.gif) no-repeat;
	height: 46px;
	line-height: 46px;
	width: 450px;
	font-size: 2em;
	font-weight: normal;
	float: left;
}
h2.trigger a {
	color: #fff;
	text-decoration: none;
	display: block;
}
h2.trigger a:hover { color: #ccc; }
h2.active {background-position: left bottom;} /*--When toggle is triggered, it will shift the image to the bottom to show its "opened" state--*/
.toggle_container {
	margin: 0 0 5px;
	padding: 0;
	border-top: 1px solid #d6d6d6;
	background: #f0f0f0 url(toggle_block_stretch.gif) repeat-y left top;
	overflow: hidden;
	font-size: 1.2em;
	width: 500px;
	clear: both;
}
.toggle_container .block {
	padding: 20px; /*--Padding of Container--*/
	background: url(toggle_block_btm.gif) no-repeat left bottom; /*--Bottom rounded corners--*/
}

Step2. Activating the Toggle with jQuery

jQuery
We will now activate this toggle effect with some simple jQuery.

$(document).ready(function(){

	//Hide (Collapse) the toggle containers on load
	$(".toggle_container").hide(); 

	//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
	$("h2.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("slow");
	});

});

Easy Toggle Tutorial - jQuery

Conclusion

I am no jQuery master, so there may be an even shorter way of writing this up, but this does the trick for me. If any jQuery heads are out there still reading, please share some of your techniques and tips!

Looking for an Accordion?

Related Articles Elsewhere

Related Posts

Author Bio

My name is Soh Tanaka and I am a Los Angeles based designer/front-end developer specializing in CSS driven web design with an emphasis on usability and search engine optimization. I also run a CSS Gallery which is updated daily with the best CSS websites from around the world. Come check it out!

You can learn more about me or Twitter  Follow me on twitter for more updates and resources!

Did You Enjoy This Post?

subscribe  Subscribe via RSS or by email to get all upcoming tutorials and articles delivered straight to you.

+ Add Comment234 Peeps Have Spoken Their Minds...

  1. Joax

    Supa fresh.. i’m gonna try to implement that to my next portfolio/site version i think :)

  2. Jae

    Looks great and very simple indeed. Thanks.

  3. evilelvi

    This helped me out a ton, thanks!

    Something I’d change is adding “cursor:pointer;” to the h2 tag so that the user gets an indication that they can click the images too.

  4. Ariyo

    nice, I like it. Thanks

  5. B. Moore

    Another great tutorial Soh!

    One thing…. you gave an example of the padding being funky an what you did to fix it. I do not know about you and everyone else but the whole piece jumps to the left when you click any of the sections. Then it will jump back to the right when you close it. But if you open 1 and get the left jump out of the way and then proceed to open the rest it wont jump back to the right until you close the last one open.

    To me that jump is way more annoying than the padding issue any day of the week.

    last thing…. in IEtab for firefox your padding issue is still there

  6. B. Moore

    Well i double checked it in a real version of IE7 and the padding issue is gone.. weird

    off topic question….
    How come you haven added your logo as a favicon for your site?

  7. Eric Roberts

    @ B. Moore – How big is your resolution and/or browser window? Are you sure opening/closing a tab isn’t causing your scroll bar to appear/disappear?

    Good tip, Soh, pretty much the exact way I control simple toggles. Keep them coming.

  8. Jonathan

    There’s a possibility to make the jQuery code much shorter:

    $(document).ready(function(){
    //Hide (Collapse) the toggle containers on load
    $(“.toggle_container”).hide();

    //Slide up and down & toogle the Class on click
    $(‘h2.trigger’).click(function(){
    $(this).toogleClass(‘active’).next(‘.toggle_container’).slideToggle(‘slow’);
    });

    });

  9. chicco

    That was soo sweet! i like it soo much.

  10. pvm

    your posts are simply the best for their clarity, a speeding application of jquery…..great

  11. dcoder405

    hi, thanks for the tips.

  12. Soh

    Thanks for the feedback, Im glad it was useful :-)

    @evilelvi good suggestion, I didnt catch that earlier!

    @B.Moore, I think eric is right, you may be seeing the vertical scroll turning on and off as the page gets longer :-p and yes, I have to get on the favicon dealio, I have been lagging!

    @Jonathan thanks for that! Just what I was looking for :-)

  13. mrbiotech

    Thanks for sharing your experience on this one!

  14. carlnunes

    Eeeewwwwuuhhh! Nice, Thanks for sharing!

  15. CyberFox

    Nice One! Thanks.

  16. pradeep

    Great tut..

    thanks

  17. Rodney

    I agree with B.Moore. The whole thing jumping to the left when the content get’s larger than the screen is really annoying. It could be ‘fixed’ with something ugly like using min-height:100% and margin-bottom:1px on the html in your CSS. This forces a vertical scrollbar in FF, which prevents the whole thing jumping to the left.

  18. Snoupix

    Nice tut, thanks a lot.

  19. Soh

    hehe if the vertical scroll really bothers you guys, you can always do

    html {
    overflow-Y: scroll;
    }

    :-)

  20. B. Moore

    yes im a dumbass for not noticing the dam scroll bar on the right but to me that is bad design.

  21. Soh

    Good point B, if you caught that as a design mistake, I’m sure there may be many others who react in the same way.

    I would say this all depends on how you use the toggle and how much content you have on the page. It will be different in each scenario :-)

  22. Rich

    very clean. good work. I could definitely see myself using this.

  23. Sérgio Soares

    another great tutorial. Thanks

  24. mick

    t y

  25. pvm

    So… i try to view slide this toggle effect in IE6… yes i have yet an IE6 user in my website… but the h2 title crash when there is a click on one of their…solutions?

  26. Stan

    is there any way I can initiate the first item to be open, and close the rest?
    at the moment it closes all of them on load,
    any assistance would be really great , thanks

  27. Stan

    I found a quick way of doing it, just declaring the first item using a different class (toggle_container0), and adding it to the javascript like:
    $(“.toggle_container”).hide();
    $(“.toggle_container0″).show();
    But it would be better if I could loop through all items and just show the first, not sure how tho.

  28. Martin

    Does not work in safari! Not useful until it’s universal for all browsers.

  29. Soh

    Are you sure you don’t have js turned off? Works for me in Mac Safari + Windows Safari~

  30. Design Jar

    Nice, I’ve been looking for something similar quite recently but because my jquery skills aren’t up to standard its be hard to integrate it in to my design. This looks pretty good and could be worth my time.

    Thanks

  31. Alberto Scozzari

    If yuo want only the first element to appear when the page is loaded just identify the first element h2 with a specific id ,like ,and then add:

    $(“#toggle_head”).click();

    at the bottom of the code

  32. Aoife

    Nice and simple and it works well! Thanks for posting this tutorial!

  33. QF

    First of all, great script. But I am having on issue with it. My .trigger class is on a div. Everything is working fine, but the div isn’t picking up the .active class. Any idea what could be causing that? Cheers.

  34. QF

    Forgot to mention, I want to the .active class to switch the position of the div’s background image.

  35. Jake

    Thanks Heaps for posting this.
    Can I possibly ask you a question?

    Do you guys know how to execute the menu to be opened in the toggle from another page?

    If you guys know, it would be much more appreciated.

    Thanks.

  36. Aoife

    Anyone know how to make this accessible for printing – so that all content displays (overriding the display: none on toggle_container).

    Thanks!

  37. John

    Great tutorial, but is there a way to make this degrade elegantly?

  38. Soh

    @ QF, if you can post a link of your example, I can take a look :-)

    @Jake, I’m not sure what you mean, do you mean have it opened with the toggle open as default?

    @Aoife great question! I just updated the sample page. What we need to do is first set up a print.css, then we will use a hack to override the inline styles. Anytime jQuery creates an action, its adding inline styles to the markup, so we would need to override that in our case.

    Print.css

    .toggle_container[style]{
    display: block !important;
    }

    for more info on overriding inline styles, check out this tutorial.

    @John, this does degraded elegantly. If you turn off js, all content is still accessible w/out any problems :-)

  39. Quick Colorado

    Wow, thanks! Here is my implementation on a live site:
    http://comicstripelpaso.com
    Click on the piggy!

  40. Joffrey

    It would be so perfect with a cookie to save the state. :)
    Could someone explain me how to do it?

    Thanks!

  41. Andrew Houle

    I just made use of this on a site that I’m doing. Thanks for the great tip and easy to follow instructions!

  42. izzy

    Thank you for this!

    One concern:

    How do I add a close button or text link inside the toggle_container so that not only the header will serve as the switch?

    Thanks again!

  43. marc

    nice one again soh,

    im with a few other people, i want to open up the 1st and 2nd on page load…

    so i have to give another id to the 2nd one too?

  44. juliane

    how can I customize it for my website?
    can I use just .trigger in my css? and not use the h2?

    i have a button image for the header that has two states: mouseon and mouseover. where do I add this command?

    can I use the code below instead of Toggle Header ?

    thanks in advance.

  45. juliane

    ops, the code below is: <div class="trigger">
    <a href="#" onmouseover="document.categories.src='images/categories2.png'"
    onmouseout="document.categories.src='images/categories1.png'"><img src="images/categories1.png" name="categories" border="0"></a>
    </div>

    instead of: <h2 class="trigger"><a href="#">Toggle Header</a></h2>

    sorry.

  46. juliane

    I got it right. thanks a lot.

    just another thing. can I toogle two different headers using the same h2.trigger?

  47. llihak

    John asked about graceful degradation. The best way is to write the page degraded and then progressively enhance it via jQuery. To that end, there is a useful technique where you place a class on the body when the document is loaded:

    $(document).ready(function(){
    $(‘body’).addClass(‘js’);
    });

    Then you can create styles like this:

    .nav { display: block; }
    .js .nav { display: none; }

    The first (default / degraded) style will apply if jQuery was not loaded and the second if it was. Using jQuery to construct any DOM elements needed for the enhanced page.

  48. thelev

    great looking output, but I cannot get it to work in wordpress. Any suggestions?

  49. Mark @ Alchemy United

    Two things…

    1) I’m with a couple others here – would like to be able to open one or more on load

    2) That said, this is the first time I’m finally dipping my toes in the jquery pool so please spoon feed the answer if possible. I don’t want to get lost and frustrated before I even get going.

    Thanks. Great post. Love it!

  50. Darren

    Is it possible to have the container open above the h2 tag instead of below?

  51. Henriette

    Hello, How close the open stuf when I clic to open an other ?

  52. Alex

    Hey everyone. First of all I love the example Soh, but I cannot get my CSS to display the background images. Any ideas why? I made images called “toggle_block_stretch.jpg” and “h2_trigger_a.gif” but still i see nothing but Times New Roman text.

    Secondly, the menu slides just fine, but I cannot change the fonts, lol. Why I wonder? Maybe my Dreamweaver is acting up? Please help!

    Thanks for the great resources!

  53. Alex

    Wow! I am a moron!

    I must have done too many undo’s and unlinked my CSS document!

    Thanks for the great code!

  54. Mark

    I think I might have found a bug in IE8. Toggling between the open state and the close state make the h2 tags overlap eachother. If you open the demo page in IE8 you’ll see what I mean.

  55. Ahmed Sagarwala

    I find this CSS a little better because it pads the href (a) 50px and not the h2.trigger. This makes the text in the block dim as you hover.

    h2.trigger {
    padding: 0;
    margin: 0 0 5px 0;
    background: url(images/h2_trigger_a.gif) no-repeat;
    height: 46px;
    line-height: 46px;
    width: 500px;
    font-size: 1.5em;
    font-weight: normal;
    } h2.trigger a {
    padding-left:50px;
    color: #fff;
    text-decoration: none;
    display: block;
    }

  56. adriancitov7

    I like it

  57. José

    Thank u!

    Great Tuto!

  58. Mark

    Thanks for the great tutorial. I’ve been struggling to get one tab to open on load and for it to behave like the others when clicked on etc (active image), has anyone had any luck with this yet?
    i tried Stan’s suggestion of:
    “I found a quick way of doing it, just declaring the first item using a different class (toggle_container0), and adding it to the javascript like:
    $(”.toggle_container”).hide();
    $(”.toggle_container0″).show();

    But i can’t get it to behave properly

  59. Mark

    Hi,
    I just sorted it, I’m no JS expert so it was trial and error, I edited the JS so it now reads:
    $(document).ready(function(){

    $(“.toggle_container”).hide();

    $(“h2.trigger”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });

    $(“.toggle_container0″).show();

    $(“h2.triggera”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });

    $(“h2.trigger”).click(function(){
    $(this).next(“.toggle_container”).slideToggle(“slow,”);

    });
    $(“h2.triggera”).click(function(){
    $(this).next(“.toggle_container0″).slideToggle(“slow,”);

    });

    });

    Added a couple of extra lines to the CSS and added a new image with the expand/contract images reversed for the tab that was to be open on load. I’m sure this is a really long winded way of doing it but it works!!

    Cheers again.

  60. website design

    Nice sliding navi! good tutorial!

  61. Michael

    Great piece of code! I just implemented a “Toggle ALL on/off” and it was tricky enough I thought I would share the code:

    // this code uses “toggle_trigger” instead of just “trigger”
    // functions to allow open all toggle_containers
    // and activate all toggle_triggers

    function toggle_all_on() {
    $(“.toggle_container”).show();
    $(“.toggle_trigger”).not(‘.active’).addClass(“active”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });
    }

    function toggle_all_off() {
    $(“.toggle_container”).hide();
    $(“.toggle_trigger.active”).removeClass(“active”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });
    }

  62. GreyK50

    Heya… Thanks for sharing this with us, I love how and what you can do in this web design field. Awesome achievement!!

    A lil noob question here.. how to change this toggle open from left to right? i mean horizontal show out…

    Thanks.

  63. Tutozed

    That was a great tut!!

    Thnx!

  64. Vivianne

    Thanks for the code! Besides wanting to toggle from a graphic on the bottom right side of the containers, I would like to have one container opened and the others closed at all times. Any ideas?

  65. FLiT

    thanks man, nicely done coz i understand it and now im using it even im just 16 years old.

  66. PG

    Hi,

    could someone please show me how to create some links at the top of the whole toggle in order to expand all / collapse all sections?

    This is great as it’s my first attempt at jquery/script!

    Thank you.
    PG :)

  67. Webagentur

    Thank you … this has me very helped.

  68. RockTK

    I found this example extremely useful. However, I was wondering if I was the only one experiencing this issue.

    Say you have a “button” to toggle a hidden pane. The pane should only be displayed hidden when you hit that button.
    The toggle works fine, the only problem I found is that when the page is loaded, the content of that pane is displayed for just an instant and then it disappears as was initially intented.

    The more complex the page is, the easier to notice it (check this example: http://roshanbh.com.np/examples/exapandable-panel/).

    It’s kind of annoying since you could hide spoilers there that you’d only want your visitors to see after clicking them.

    I’ve tried several browsers (ff, opera, chrome, ie) and it always happens to some extent. In some, it’s almost unnoticeable.

    Is there any workaround to “hard-hide” that pane’s content?

    Maybe I’m taking crazy pills though :p

  69. Soh

    You can set a display: none; in your css and have your js change it to display: block; once its loaded to fix that*~ You are stumbling on that problem because the content is not hidden until the javascript is loaded and triggered.

    But…

    *The downside: If your user does not have js enabled, your users will not be able to see your content at all, and it becomes an accessibility issue.

    The good thing about this tutorial is that it degrades gracefully, but it does have that split second where the toggle is open until the script is loaded~

  70. RockTK

    Thanks a lot for your suggestion, Soh.
    A guy I know suggested something very similar and quite simple.

    For the newbies that don’t know how to do it, basically, you leave the CSS attributes for the toggle_container intact. The display attribute is set on the div itself:

    As you mentioned, there’s the downside that the content will not be shown for clients with javascript disabled.

  71. Prasanna Jathan

    This is my favorite blog. Gone through almost every article. Almost all articles are briefed very well.
    Thank you.

  72. Steo

    This is so cool…i think i’m going to use it in my blog :D

  73. Dirk

    hi, how is it possible to close an open one by clicking/opening a other one ?????

    (asked before by diff. persons but no one seems to have a solution…?)

  74. Novianto

    Hi, great post.
    is it possible to retrieve data from MySQL table in it? So if you expand the box, you will get dynamic data from MySQL table. Please help..

  75. Bryan

    I’m sorry to have to ask such a royal newb question…

    But where do you paste the jquery script?

    Can I just paste it in between a tags in the header.php of my wp blog?

    bryan

  76. Soh

    Hey Bryan, no worries :-)

    You would put your js code inbetween tags like this

    <script type="text/javascript" src="jqueryfilegoeshere.js"></script>
    <script type="text/javascript">

    $(document).ready(function(){

    });

    </script>

    and although you can put it up at your header.php, they recommend its more efficient when placed at the bottom of your source code~

  77. gaus surahman

    Actually I found a simpler and reusable version somewhere in the same site and thought it might be worth sharing here. We create a custom method to make our code more reusable across different places.


    jQuery.fn.slideDownToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
    };

    See the property “height”, it may also be replaced with “width” to create a sliding horizontal block, just make sure to create a different function, says slideHorizonToggle.

    Now we have this custom function, we can make it avalaible in several places:

    $("h2.trigger").click(function(){
    $(this).next(".toggle_container").slideDownToggle("slow");
    $(this).toggleClass("active"); return false;
    });

    You may see it implemented in my site tutorials to create a facebook-like chat panel and a sexy collapsible horizontal login block.
    Thanks.

  78. Gonzalo Aguilera

    Yes very simple and great looking. I have not idea about JQUERY and will appreciate your recommendation: I have an application that when the user EXPAND a record, instead of statiic information, I show details information using an AJAX call to the Database to populate the content panel and show it. This is done one once per node/session and only when the user EXPAND. How can I do that using JQUERY?

    Thanks!

  79. netmastan

    Thanks. The problem is if there is another div after h2 element other then toggle_container it doesn’t work. Does anyone knows how to solve this?

    For example.

    Click to expand
    David jackskon
    Here goes David’s bio

  80. syed@New Zealand

    Thanks for this great tutorial. Here is a modified version which I needed for a project. When you expand a div I wanted to close all the but the current one. For some reason toggle expand was not smooth..so I’ve increased the toggle speed.. I thought it might be useful for some people.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Expand example</title>
    <style type="text/css">
    body{margin:0;padding:0; font-family:Georgia, "Times New Roman", Times, serif}

    .info{background-color:#ffffff; padding:20px; margin-bottom:20px; display:none}
    .name{margin-bottom:10px; padding-top:5px; width:650px}
    .info img{float:left}
    .info p{margin-left:70px; margin-top:0}

    #container{width:700px; margin:auto}
    h2.name{font-size:12px; font-weight:normal; background:url(../images/plus.gif) 620px 5px no-repeat; cursor:pointer}
    h2 span{font-weight:bold;color:#FB040A; }
    span.plus{ cursor:pointer; }
    span.plus img{padding-right:20px; float:right}
    h2.active{background:url(../images/minus.gif) 620px 5px no-repeat; cursor:pointer}

    </style>
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

    $(document).ready(function(){
    $("h2.name").click(function(){

    $(this).next(".info").slideToggle(100);
    $(".info").hide();

    if($(this).hasClass("active") ){
    $(this).removeClass("active");
    }else{
    $("h2").removeClass("active");
    $(this).addClass("active");
    }
    return false;

    });

    });
    </script>
    </head>
    <body>
    <div id="container">
    <h2 class="name"><span>Syed Rasel,</span> Director </h2>
    <div class="info"> <img src="images/box.gif"/>
    <p> Rutrum a hendrerit quis, pretium vel nulla. Vestibulum aliquet, ante sit amet ornare imperdiet, felis est gravida arcu, sed sodales metus ipsum a massa. Curabitur sagittis lorem ut nisi tincidunt vitae bibendum eros fermentum. Sed sapien ipsum, dapibus id consequat ac, adipiscing sit amet quam. Donec sed metus lacus. Fusce sed neque id arcu viverra vulputate a nec elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lobortis magna eget turpis lacinia vestibulum. Ut purus urna, vestibulum ut commodo eget, cursus ac sem. Donec eget tortor mauris. Maecenas quis arcu vel lorem eleifend molestie et quis erat. </p>
    </div>
    <h2 class="name"><span>Rasel Syed</span> General Manager </h2>
    <div class="info"> <img src="images/box.gif"/>
    <p> Ante sit amet ornare imperdiet, felis est gravida arcu, sed sodales metus ipsum a massa. Curabitur sagittis lorem ut nisi tincidunt vitae bibendum eros fermentum. Sed sapien ipsum, dapibus id consequat ac, adipiscing sit amet quam. Donec sed metus lacus. Fusce sed neque id arcu viverra vulputate a nec elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lobortis magna eget turpis lacinia vestibulum. Ut purus urna, vestibulum ut commodo eget, cursus ac sem. Donec eget tortor mauris. Maecenas quis arcu vel lorem eleifend molestie et quis erat. </p>
    </div>
    </div>
    </body>
    </html>

  81. Indigo

    Hi – this is a really helpful and simple to implement script – thanks.

    I am using this for a list of recipes, so I can put them on one page. Is there a way of opening a specific toggle from a link, similar to ponting to an anchor. Only I have so may recipes that I want state a list at the top that when each is clicked the approriate toggle is targeted and opened.

    Have tried javascript ‘on-click’ to no avail – HELP ANYONE??

  82. THE FiSH

    Hi all,

    First off, great script and a wonderful starting point. Second, I’m using this to create a Custom CMS for a client, and I’m using this to give everything some visual flair.

    However, this script didn’t do one thing that I was wanting it to do, and that’s open the section clicked one AND close any other section that may be open. That way you only have one section open at a time.

    I must also note that I’m extremely new to jquery but after a bit of research and understanding how everything works together… this is what I’ve come up with.

    I hope this helps anyone that was wanting to do something similar to what I wanted and good luck to everyone.

    //Hide (Collapse) the toggle containers on load
    $(“.toggle_container”).hide();

    $(‘h2.trigger’).click(function() {
    if ( $(‘h2.trigger’).hasClass(“active”) ) {
    $(‘h2.trigger’).removeClass(“active”);
    } else {
    $(this).addClass(“active”);
    }
    var $nextDiv = $(this).next();
    var $visibleSiblings = $nextDiv.siblings(‘div:visible’);
    if ($visibleSiblings.length ) {
    $(this).addClass(“active”);
    $visibleSiblings.slideUp(‘fast’, function() {
    $nextDiv.slideToggle(‘fast’);
    });
    } else {
    $nextDiv.slideToggle(‘fast’);
    }
    });

  83. Indigo

    Tried this to toggle from above link – didn’t work – anyone help?

    $(function(){
    $(“h2.trigger .toggle_container”).hide();

    $(“#recipes td a”).each(function(index) {
    $(this).click(function() {
    var id = $(this).attr(‘href’);
    var $thisDiv = $(id);

    if ($thisDiv.siblings(‘:visible’).length) {
    $thisDiv.siblings(‘:visible’).slideUp(700, function() {
    $thisDiv.slideDown();
    });
    } else {
    $thisDiv.slideToggle();
    }
    return false;
    });
    });
    });

    I’ve assigned each toggle trigger with an id. I just want to be able to open each from an additional top link also — any tips ANYONE? This is driving me crazy.

    Page I’m working on: http://www.essexgourmet.co.uk/recipes_test.php

    Many thanks.

  84. THE FiSH

    What’s going on Indigo?

    I see what you’re trying to do here and I think it can be easily done. Now I haven’t tested any of this, but I think it should work… if you have any questions ask away.

    first, you’ll want to add this to you javascript at the top of the page:

    $(“.link_3″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });
    $(“.link_2″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });

    second, you’ll want to change your sections that are opening up to look like this:

    Baked Ratatouille Recipe

    you should note that the id for the h2 will be created using your php variable… something like

    also, you need quotes around everything, like in the above H2 code and caps are generally not good.

    third, the link that you’re clicking should look like this:

    Baked Ratatouille

    again your ID is coming from your php but I would assume that you already know all this.

    If this doesn’t work right off… it should get you really close. The error would come with that javascript up there and the whole variable deal. Again, I’m really new to this stuff, but i think it should work.

  85. THE FiSH

    sorry about that…. lest try it again and see if the code will show up.

    What’s going on Indigo?

    I see what you’re trying to do here and I think it can be easily done. Now I haven’t tested any of this, but I think it should work… if you have any questions ask away.

    first, you’ll want to add this to you javascript at the top of the page:

    $(“.link_3″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });
    $(“.link_2″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });

    second, you’ll want to change your sections that are opening up to look like this:

    <h2 class=”trigger” id=”recipe-1″><a href=”#”>Baked Ratatouille Recipe</a></h2>

    you should note that the id for the h2 will be created using your php variable… something like <?php echo “recipe-” . $id; ?>

    also, you need quotes around everything, like in the above H2 code and caps are generally not good.

    third, the link that you’re clicking should look like this:

    <a href=”#1″ class=”link_3″ id=”1″>Baked Ratatouille</a>

    again your ID is coming from your php but I would assume that you already know all this.

    If this doesn’t work right off… it should get you really close. The error would come with that javascript up there and the whole variable deal. Again, I’m really new to this stuff, but i think it should work.

  86. Indigo

    Thanks ‘THE FISH’ for your help, it’s so appreciated that you took an interest in my prob.

    I have implemented your code and advice, although recieve the following error:

    “Object doesn’t support this property or method” Pointing to the 1st line of the code you gave to add to current jquery function.

    This is what I have added:
    SCRIPT:
    $(document).ready(function(){

    $(“.toggle_container”).hide();

    $(“h2.trigger”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });

    $(“h2.trigger”).click(function(){
    $(this).next(“.toggle_container”).slideToggle(“slow,”);
    });

    $(“.link_3″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });

    $(“.link_2″).click(function(){
    var recipeID = “h2#recipe-” + $(this).getAttribute(‘id’);
    $(recipeID).next(“.toggle_container”).slideDown(“fast”);
    });
    });

    H2 TRIGGER:
    <h2 class=”trigger” id=”recipe-”> Recipe

    TOP LINK:
    <a href=”#” class=”link_2″ id=”">

    Do I need to include a jquery UI??

    Many Thanks.

  87. Indigo

    Oops, adding PHP code messed up above, correction on bottom bit:

    H2 TRIGGER:
    RECIPE TITLE TRIGGER HERE

    TOP LINK:
    RECIPE TITLE LINK HERE

    Thanks.

  88. Indigo

    Third Time Lucky…

    H2 Trigger:
    <h2 class="trigger" id="recipe-1>"><a href="#">RECIPE TITLE TRIGGER HERE</a></h2>

    Top Link:
    <a href="#1" class="link_2" id="1">RECIPE LINK TITLE HERE</a>

    (sigh!)

  89. THE FiSH

    Hey Indigo, shoot me an email and we’ll see if we can get all this figured out.

    rherring@fish-graphics.com

  90. Skywalker

    Hey, great tutorial, and even better website. But can someone please help me out? I’ve tried everything, and I can’t get it to have container open on load (I’m not great at Javascript and while a number of people have pointed out a solution, they’ve not provided any detail for noobs like me).

    Thanks! :)

  91. PG

    Hi,

    URGENT PROBLEM IN IE8!

    As Mark reported back in May -

    “I think I might have found a bug in IE8. Toggling between the open state and the close state make the h2 tags overlap eachother. If you open the demo page in IE8 you’ll see what I mean.”

    Please check this out as sections disappear!

    I’ve just implemented this for someone on their website and I don’t know how to fix it!

    Thanks
    PG

  92. Soh

    Hey PG,

    I just tested this again in IE8 and can’t seem to get that bug to appear… :-(

  93. David

    Soh, nice example of this technique. I’ve actually used similar but not based on the jquery library and so I have a question. You noted in an comment that jquery writes inline styles – I’m wondering why is that necessary?

    If you write the CSS that covers both an open and closed div, for example, and these are driven by selectors based on class names such as “expanded” and “closed”, then all it should take is having jquery swap in and out the appropriate class names. No need to apply inline styles. Right? Or are the inline styles required b/c of the animation (i.e. the transition btwn closed and open) effect?

  94. PG

    Hi Soh,

    thanks for checking.

    I tried this just now on IE8 (v 8.0.6001.18372.xpsp_sp2_rtm.040803-2158) running in Parallels VM on my Mac and the problem is still there.

    Any ideas?

    Also, on IE6, I’ve had problems where the first & last sections appear, with a gap between them where the other sections (h2) should be. As soon as I click on the first section the others appear in the gap?…

    Thanks
    PG

  95. PG

    Hi Soh,

    just upgraded IE8 to latest version (8.0.6001.18702) and this problem seems to have gone away.
    However, there’s a new problem!

    When the last of any open toggles are closed, the whole accordion shifts up flush against the preceding paragraph (where there was a gap before. margin-bottom on the P tag)

    This makes the whole things move up and down on subsequent open & close actions – any thoughts?

    Also the IE6 issue remains.

    Thanks Soh
    PG

  96. Soh

    Sorry PG, unless I can get a clear visual of what the bug is I won’t be able to debug this :-(

    Everything seems to be working fine on my end, any one else having similar issues?

  97. Knightmare

    Greetings, soh.

    Excellent tutorial. I really liked it. However, I seem to be having a problem implementing it on a website I am using. If I place the code into a page all of its own, it works beautifully.

    However, if I try to put the scripts into a dynamically loaded user control, it fires the jQuery as the main page is loaded, and never hooks into the user control as it is rendered. I am beginning to get frustrated with the way it is working, as this is exactly what the site needs. Any way to help?

    Knightmare

  98. Knightmare

    Found what I needed. Had to use the PageRequestManager to re-bind to the event every time the updatepanel was updated. Now it fires, and works like a charm…. Off to bind lists, and dynamically create more. *LOL*

  99. PG

    Hi Soh,

    can I send you a link to the sites in question?
    They’re not public yet, so don’t want to post urls here.

    Where should I send URLs to?

    Thanks
    PG

  100. PG

    Hi Soh,

    just tried sending you details via your contact form, but it failed with “This address no longer accepts mail”.
    How can I get URL details to you?

    Thanks
    PG

  101. Soh

    hey PG, you can send them to info(at)sohtanaka(dot)com

  102. PG

    on it’s way – thanks!

    Regards
    PG

  103. TALLBOY

    @pvm – i ran into that crash in IE6 as well. In the JS there’s this .slideToggle(“slow,”); – the IE6 browser fails on the comma. Remove the comma and you should be fine.

  104. Erik

    Absolutely love this!! BUT, is it possible to open them all at once? and close them all at once? Is it possible to open one and close the others at the same time?

    Erik

  105. Erik

    How do you make only one is open at one time always. Your closing one when opening another…..

    Many thanks.

    Erik

  106. Ann

    Great script. Works like a charm! However, the headers seem way too large. Tried to find a way to change this in the CSS but couldn’t find the code for it.

  107. Soh

    @David yes you can swap classes and have the css written in the stylesheet, but I believe using .hide and .show actually puts a diplay:block/none inline (please correct me if im wrong). I usually highlight the element in firefox, then view selection source, and you can see that it adds inline styles. I was under the assumption that this was the reason possibly why the print style sheet was not working. Sorry for the late reply btw :-p

    @Knightmare you may have to call the jquery event when the user control is loaded. I had similar issues before where the jquery fired off before the user control was called. I had to call the event afterwards and it worked for me~

    @Erik if you want to close/open all at once you can do:
    $("h2.trigger").click(function(){
    $(".toggle_container").slideToggle("slow");
    });

    for having one open at all times, you should be looking into an accordion instead of a toggle element. Maybe something like this: http://www.sohtanaka.com/web-design/styling-an-accordion-with-css/

    @Ann you can change the font-size in the h2.trigger~

  108. SEan

    Any way to implement this into wordpress

  109. Neel

    Excellent tutorial to create Expand Collapse. Design is too good as there is no content on the example page the right hand scroller comes when it expands.. But if you have content on your site then you will not notice it.
    Great work..

  110. Andy

    Hi,I found a bug,show all default,screen will twinkling when you slied up from last one,how resolve the problem,Thanks.

  111. Soh

    Andy are you talking about the glitch when the content passed the viewport? If so that is a vertical scroll appearing and disappearing causing it to look like a glitch.

    you can get rid of that issue by always having a vertical scroll

    html {
    overflow-Y: scroll;
    }

  112. Andy

    better after add that code,thanks~

  113. Dorith

    Really nice, will use for my website!

  114. Ramil

    Do you have any plans on updating the code to use cookies to remember the toggle state?

  115. nidcha

    Thanks! That’s really good and easy for modification.

  116. ted

    Thanks!

    Also vote for cookie!

  117. ted

    Here is a good example for using jQuery cookie in toggle:
    http://www.bramme.net/2008/09/a-jquery-slider-on-cookies/

  118. Ramil

    Soh, we’re patiently waiting for the cookie version. Also with your jQuery Tabs ;)

  119. Soh

    Sorry guys, I have been extremely crammed with work recently, and to be honest I won’t be able to update this tut with any extra features for a little while longer~ For those with extra feature requests that do not relate to the original tutorial itself, I apologize for the inconvenience.

    Just as a hint though, I would be using this plugin for jQuery to get this going. http://plugins.jquery.com/project/Cookie

    Thanks~

  120. Brad

    Soh,

    Great job, thanks for sharing. Question, how do I expand the first block on page load or default. thanks in advance!

  121. Skywalker

    Guys I need some help…

    I inlcuded some Flash content within the toggle box, and it doesn’t seem to slide up when I close the panel in FF (works in IE). It instead stays on screen and then vanishes a few seconds later.

    Any help?

  122. Kevin Pajak

    Hey Soh, fantastic tutorial here! So helpful… Just have one question/point (sorry if it’s already been covered here, but I have been looking all over to find a resolution for this and still can not yet). All works well with the toggle except for a minor “flickering” in IE7 upon closing the toggle back up again to the original state. What happens is the content box will be open/displayed [-]. Then you click on the [-] to close the box, and the content area below disappears, flickers on again for one quick second, then disappears again (as usual it is that buggy IE causing issues). I see thought that it does not do this on your original page when I check it in IE! (btw: all is totally fine for me in Firefox). I did notice that you called the code:

    .toggle_container[style]{
    display: block !important;}

    in your print.css file, but I can seem to resolve this issue. Anyone have any ideas? Thanks a bunch in advance. :-].

  123. doublemind

    Hi,

    I have used this on my site and love it.

    I have a situition in which i can’t make it to work. I have a report that takes little long to show. Here actual calculation part is done by another page (child) and i get this child on the page via ajax and then display it inside a div tag.

    As soon as the parent page loads, i show a message that your report is being prepared and also show an animated gif. As soon as the report shows, busy message and animation hides. At this point, by default, divs with ‘toggle_containers’ should not be visible but on my parent page these are. I have tried this by putting the js and css files on the parent page, on the child page and infact on both the pages at the same time. Also, when i click, nothing heppens.

    Here is the code that gets the calculation and then displays on the page
    <script type="text/javascript">
    $(document).ready(function() {
    ShowActivityReport();
    });

    function ShowActivityReport()
    {
    $('#reportView').html(''); //reportView is div to show report in.
    $.get("report.asp",function(data){
    $('#reportView').html(data);
    $('#reportView').fadeIn();
    $('#contentLoadingMessage').hide();
    });
    }
    </script>

  124. öğrenme nesneleri

    Perfect application. Thanks

  125. Will

    @Kevin, I have the same issue but it’s in a different circumstance. Still Googling but with no luck.

  126. Evan Smith

    @B.Moore @Soh The twitchy scroll problem is how I came upon your post. I was looking to set an overflow:hidden; to the page upon clicking a top login (sliding div), and then change it back to overflow:auto; while closing the top login. I’ll give your html overflow-y scroll a try. From my past solution-attempts I recall Safari being the only browser that played well with scrolls (it always had the reserved space for it). But defaulting the scroll to the html didn’t work for all browsers (from my recollection), and putting a scroll on the body ended up being ridiculous (because there would be 2 sets of scrolls side by side).

  127. Clay

    DAMMN BOI! This is rad.

  128. Jabga

    Umm, it was great !

  129. paul

    thanks alot for this, i have been wondering why my attempts didnt work, but its the next. bit.

    keep up the great work, your helping my career :)

  130. Matt

    Hi SOH and thanks really much for this great script, the best and well coded so far.
    i’m thinking of using this for a wordpress blog, but a question remains: how will the open/closed state will be saved/stored so that when WordPress relaunches the page the boxes dont start all closed again?
    I guess there is a start of solution with cookies and to force the style but I’m not a developper…
    Have you got a solution?
    Many thanks

  131. Julian

    I would like to use a vertical, collapsable menu. normally if you click on a menu item, the sub items collapse and only the sub items have a link to a page. but I would like to have pages in the main items too! in other words, when I press a menu link, it slides open and also opens a page url.

    unfortunately I ‘m still learning with jquery and I go the next code wich works but doesn’t open a page in the main menu but only slides open with the sub items. these sub items do link to pages.

    can anybody please help me to figure out the code for opening a slider and opening a page at the same mouse event?

    here is the code, thanks for the response!

    $(document).ready(function(){
    $(“dd:all(:first)”).hide();
    $(“dt a”).click(function(){
    $(“dd:visible”).slideUp(“fast”);
    $(this).parent().next().slideDown(“fast”);
    $(‘.link’).removeClass(‘active’);
    $(this).toggleClass(“active”);
    //$(“dt a”).load(this.href);
    return false;
    });
    });

  132. Andy Feliciotti

    Great tut, thanks!

  133. Sam Sullivan

    LOvely bit of code.

    Is it possible to add html under or in the h2 trigger? eg.

    <h2 class="trigger"><a href="#">Web Design Development</a></h2>

    <—add my html code here—>

    <div class="toggle_container">
    <div class="block">

  134. Jessie

    How can I change this so that when the trigger is clicked it doesn’t move or affect the position of the other triggers? I want the content boxes to slide open like the original version, but I want them to do so without the triggers ever moving. Basically I want to place the triggers independently from where the boxes are placed. Any ideas?

  135. Jessie

    Its looking like I figured it out… just had to create id’s with absolute positioning in conjunction with every h2.trigger. Then position the .toggle_container where I wanted it using relative positioning.

  136. james

    Where in the code can i place the images instead of toggle header option

  137. Eddie

    Hi,

    The toggle effect looks really really awesome. Just recently found out the name of this feature.
    The code seems doable so I tried to implement it:
    I created a .html file, a .css file and a .js file (with the jquery script), with contents copied from the top of this webpage. Linked the .css and .js file in the HEAD to the .html file and previewed it in the browser. I must be doing something very wrong, because the result isn’t what I hoped for/expected. I have some experience with javascript, but am completely new to jquery. Can anyone help me by telling what I’mm doing wrong?

  138. hitesh

    thanks man you work is just awesome

  139. Avangelist

    I am curious as to why you’ve used show/hide and not toggle – being there is already a jQuery function available why not use it?

    I am at present using toggle, but have noticed that the out transition doesn’t work in IE7/8 but does when you slide back in. I am using blind for my effect.

    I have also noticed that there is screen flicker with IE7/8 has anyone else seen this behaviour when show/hiding div’s and how did you resolve it?

  140. new user

    Hey, great tutorial but i m experience the flicker in mozilla firefox.
    can anyone help me out with this issue.
    Thanks in advance.

  141. Craig

    Hi new user – I think the flicker in Firefox shouldn’t be so bad if you change $(this).next(“.toggle_container”).slideToggle(“slow”);

    to

    $(this).next(“.toggle_container”).slideToggle(“fast”);

    This should speed up the toggle speed and you shouldn’t notice any flicker.. I’m no jQuery pro so there maybe a better solution.

    PS: Great post!

  142. joe user

    This isnt so much a show/hid rather than an accordion

  143. Steve

    Fantastic post! Very helpful. I have one question though, regarding the advice…

    “@Erik if you want to close/open all at once you can do:
    $(“h2.trigger”).click(function(){
    $(“.toggle_container”).slideToggle(“slow”);
    });”

    This will open/close all elements only if they are closed to begin with. It doesn’t work properly if any of the elements are already expanded. ie. it just toggles the hide/show state of everything, except the elements that are already open. any ideas?

  144. NoName4me

    I’m sorry, but changing
    (”.toggle_container”).slideToggle(”slow”);

    to

    $(this).next(”.toggle_container”).slideToggle(”fast”);

    doesnt help..

    Anyone has a solution for this problem with the flicker to the left? It appears in IE8 and FF 3.5

  145. SteveP

    I use this code and it works brilliantly but I have a specific situation that creates a flicker in Firefox.
    The situation was when the expanding element goes longer than the page and a vertical scrollbar appears in Firefox. If you scroll down to read all of the text in the expanding element and then click on the trigger to close the element, Firefox would flash for a second and then the page readjusts and returns to its position before the expanded element was expanded.
    I have tried adding ‘return false;’ to no avail.

  146. Soh

    Sorry guys, I would love to help but I am using firefox and do not see any flicker on my demos~ If anyone can show me an example I can def investigate, but as far as on my end and demo, it is running smooth for me.

  147. Jon B

    Hi Soh. I think the flicker happens when you have a lot of html items in your toggle div. In my div, it flickers when I use a UL with about 30 LI items.

  148. Denny

    Is available for blogspot.com?

  149. Dr. N

    I like it, very simple, Thx

  150. Prameela

    Where can I download this demo…?

  151. Ervald

    @Stan:

    To make the first/last active add another line in js like this:

    For first

    $(".toggle_container").hide();
    $(".toggle_container:first").show();

    For last

    $(".toggle_container").hide();
    $(".toggle_container:last").show();

  152. Crag

    The flicker can be cured by clearing the toggle_container div of floats. It is when the toggle_container div doesn’t stretch to fit when the block is revealed that seems to be the problem.

    I have a class .clear{ clear: both } in my stylesheet then I just place directly below the toggle_container class.

    This fixed the flicker for me.

  153. kaiser

    works like a charm! thanks a lot!

  154. indialike

    Very nice and useful tutorials to web designers,
    Thanks for posting.

  155. Bockerl

    Thank you … that is very nice and this has me very helped.

  156. Jonathan Goodman

    Hey Soh, thanks for your tutorial here. its been a great help so far.

    I’ve hit a small problem with IE 8 which is when I click on some of the triggers on my page the block for a different trigger opens too.

    I guess the best way to see what I mean is by looking at this page here:
    http://hotcoalstairs.com/nbl/ie/index.php?

    I’m happy with how the page appears on chrome, ff and safari. Its just IE thats the problem. Not sure whats going on. Very new to web design.

  157. Brian

    Fantastic script!

    I’m using this on the ThemeJam options panel.

    I had one additional requirement, and that was to add a “close” link at the bottom of the opened div. Here’s the additional code I used…

    HTML:

    <h2 class="trigger"><a href="#">Toggle Header</a></h2>
    <div class="toggle_container">
    <div class="block">
    <h3>Content Header</h3>
    <!–Content–>
    <p class="close">Close</p>
    </div>
    </div>

    CSS:

    p.close {
    curser: pointer;
    }

    JQUERY:

    //Close the containing panel
    $("p.close").click(function(){
    $(this).parent().hide(300);
    });

    Hope this helps :)

  158. MXCV

    Thank you for this! Got it to work no problems.

    Question though any way to get this to automatically close an open panel when opening a new one. In other words is there any way to make it so that there can be no more than one panel open at one time.

  159. Axel

    I have a problem… I have this code:

    <a href="#"><div class="trigger">Gravuren</div></a>
    <div class="toggle_container">
    <a href="gravuren.php?categorie=ringe"><div class="submenulink">Ringe</div></a>
    </div>

    In the first line there is the link, like your h2 (it’s just that I don’t will to use h2…)
    then there is the toggle container, wich I want to expand when you click on the link.
    Then in comes the “contained”.
    The problem is that it doesn’t work…
    Can you give me the modified jquery code?
    I used this, but it doesn’t work…:

    $(document).ready(function(){

    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide();

    //Switch the "Open" and "Close" state per click
    $("div.trigger").toggle(function(){
    $(this).addClass("active");
    }, function () {
    $(this).removeClass("active");
    });

    //Slide up and down on click
    $("div.trigger").click(function(){
    $(this).next(".toggle_container").slideToggle("slow");
    });

    });

    Thank’s a lot for this tutorial!

    axel

  160. Ivan Mišić

    Great tutorijal :-) just keep in that way

  161. Jessica Dooley

    Great example!!! I like it :)

  162. Jules

    Thank you for sharing, great script.

    I wanted to force some toggles to be open on load so I added a class “.opened”
    $(".toggle_container, .opened").show();

    This works just fine, but I don’t know how to get the “.active” class added to the h tag when forcing the .toggle-container open with my new class. Does anyone have any suggestions?

    Thanks! ~ Jules

  163. Jules

    Hello again:-)

    Well I figured out a way to force certain toggle containers open on load and how to get the .active class to toggle correctly between my forced open on load containers. Since this is definitely not my area of expertise the code is probably not as streamlined as it could be. I’d love to hear some feedback if anyone knows of a better way.

    ~Jules

    $(document).ready(function(){

    //Hide (Collapse) the toggle containers on load
    $(".toggle-container").hide();

    //Switch the "Open" and "Close" state per click
    $("h3.trigger").toggle(function(){
    $(this).addClass("active");
    }, function () {
    $(this).removeClass("active");
    });

    // Open toggle containers on load with class of .opened
    $(".opened").show();

    //Switch the "Open" and "Close" state of toggle containers that are open on load
    $("h3.trigger-open").toggle(function(){
    $(this).removeClass("active");
    }, function () {
    $(this).addClass("active");
    });

    //Slide up and down on click – included both open and collapsed toggle containers
    $("h3.trigger, h3.trigger-open").click(function(){
    $(this).next(".toggle-container").slideToggle("slow");
    });

    });

  164. drooh

    thanks

  165. Donovan

    Jules can you shoot a link to a page where your solution has been used. I’m looking to obtain the same effect. – Thanks!

  166. Gokhan

    Is there any cookie writing code for toggling containers, because when visitor clicks to open some container on the sidebar then changes the page it turns back collapsed again.

  167. Heike

    Thanks a lot.
    I was looking for a solution to get the whole content printed cause jquery toggle uses inline styles “display:none” … And here I found such an easy way to do with 3 lines of css ;-)

  168. mose

    hey there

    i have implememted this, and it works fine in IE8, FF and Chrome. but it refuses to work in IE7.

    what am i doing wrong?

    http://bit.ly/a4wlWn

    any help appreciated!

    Thanks

  169. david stranack

    Hi guys,

    Greeeeeat tutorial, thanks man!!

    But can anyone help a total newbie to have the top container to be open on load PLEEEEEASE???? I have seen Marks comment about it above & I have tried to play around with the code BUT cannot get it working :-(

  170. David Parker

    I’m new to jQuery, and have been looking to show/hide the content of a tab.
    1. I recently read that if the div tag is hidden that your try to write to that it was not able to.
    2. It was suggested that if it is your intent to over write a hidden div on a different tab that, you should move the div off the viewable space (negative positioning). That way you can write to it.

    Does any of this ring a bell?
    I can not find the site where I read this.

  171. Chris

    Love this and I’m going to use it on my personal site.

    Question, does anyone know what would need to be added so that only ONE panel can be open at a time?

    So if you open one and then click on the next one it will open and the previously open one will close? So only one can be open at a time?

  172. daddy design

    great article. going to use this tip!!

  173. paul

    Awesome! This is exactly what I needed. Thank you!

  174. Sagar

    I am facing a problem whenever I am trying to use this toggle function.
    I have an overlay created at onClick event on a page. Now there is another onClick event on the overlay which has this toggle functions like expand and collapse. But I want that overlay to take care of the height and width dynamically. I dont want the scroll bars to appear at oinClick event so that it can fit the size of the window in it.
    It would be of great help if anyone can help me out with this.

  175. Ahmad Qazi

    Great article.

  176. Brian

    Any way to get them to close when a new one is opened, like an accordian?

  177. chris raymond

    Will this script work with jQuery 1.2? Updating to jquery 1.4 is not an option for the site I am doing work for.

  178. ake

    Thank you for this!

  179. asdf

    thanks!

  180. Jorge

    Me parece muy bueno este tutorial ..gracias por compartir amigo.

  181. Andre

    I’ve noticed that if you just do [ .toggle(slow); ] instead of [toggleSlide] right before [return true] , it has a cooler effect.

    Thanks for the tutorial. This has been a great help!

    $(document).ready(function(){

    $(“.toggle_container”).hide();

    $(“h2.trigger”).toggle(function(){
    $(this).addClass(“active”);
    }, function () {
    $(this).removeClass(“active”);
    });

    $(“h2.trigger”).click (function() {
    $(this).next (‘.toggle_container’).toggle(‘slow’);
    return true;
    });
    });

  182. Sebastian Wolf

    Thank you, it really helped me, used it on my homepage http://www.mail-wolf.de

  183. George

    Any way to properly nest one toggle within another? I’ve attempted it however the nested h2 font size seems to render larger than the first.

  184. Nicholas

    Short and sweet, very nice tut. I am going to try to use it on my blog to hide and show certain social media icons below the post (I hate the way they clutter up the page now), I will let you know if it works out.

    Side note: don’t forget to update your copyright to 2010. Keep up the great work!

  185. Raceweek

    Fantastic script,

    Exactly what we were after.

  186. Chris Pangburn

    Many thanks for the example, it’s easy to customise and install – will definitely put it to use.

  187. mike

    thanks dude!

  188. Robin

    Does anyone know how to make a proper open/close all button for this? This best I can get is to toggle alternative states.

    Great script btw.

  189. Robin

    I found a way to have seperate “Open all” and “Close all” links.

    // Open/close all
    $("a.open_all").click(function(){
    $(".toggle_container").slideDown("fast");
    $("h3.trigger").removeClass("active");
    });

    $("a.close_all").click(function(){
    $(".toggle_container").slideUp("fast");
    $("h3.trigger").addClass("active");
    });

    //Switch the "Open" and "Close" state per click
    $("h3.trigger").toggle(function(){
    $(this).addClass("active");
    }, function () {
    $(this).removeClass("active");
    });

  190. Robin

    Or better yet and toggle all button.

    // Toogle ALL button
    $("a.toggle_all").toggle(function(){
    $(".toggle_container").slideUp(80);
    $("h3.trigger").addClass("active");}, function () {
    $("h3.trigger").removeClass("active");
    $(".toggle_container").slideDown(80);
    });

    $('a.toggle_all').click(function() {
    $(this).text($(this).text() == ' Open All' ? '- Close All' : ' Open All');
    return false;
    });

    // Switch the "Open" and "Close" state per click
    $("h3.trigger").toggle(function(){
    $(this).addClass("active");}, function () {
    $(this).removeClass("active");
    return false;
    });

    // Slide up and down on click
    $("h3.trigger").click(function(){
    $(this).next(".toggle_container").toggle(0);
    return false;
    });

  191. Ian

    I have just had a quick look and your site is awesome. You have a great design skill. I will be back. Good Luck!

  192. John Crumpton

    Thanks! Does anyone know how I’d make Robin’s toggle all into a html link? Thanks

  193. John Crumpton

    a href=”#” class=”toggle_all”

  194. Mali

    What a cool script, thanks a lot Soh.

    I just have few questions, how do show first item onload and close open item when toggle new item – show one @the time?

    Cheers,
    MALI

  195. Sahaj

    Thanks for this easy tutorial.
    Only I wish to put the trigger bar at the bottom of the container.
    Any idea how to do it?

  196. Jason Day

    OK, the workaround above for having one toggle open at a time is not working for me. Can someone post the full code that they used to get that to work?

    Thanks!

  197. Ellen

    After trying to open the first element and where click() method didn’t work, I came up with a simple idea. I gave the first .trigger an id of the “first-item”. Then the code become very simple:

    Title
    ……

    jQuery:

    $(“.toggle_container”).hide();
    $(“#first-item”).toggleClass(“active”);
    $(“#first-item”).next().show();

    $(“.trigger”).click(function() {
    $(this).toggleClass(“active”).next().slideToggle(“slow”);
    });

  198. Eliza

    I really like this one but How do I make it slide out from the left instead of up and down???? HELP!!!

  199. Palak Soni

    Nice and great simple tutorial it works well! Thanks for posting this tutorial!

  200. Mike Raynham

    Hi,

    I found your article while researching for an article I was writing. I used a similar approach, and then expanded it to resolve some of the accessibility issues. It also inlcudes code which allows one or more sections to be declared as visible / expanded when the page loads:

    http://www.mikeraynham.co.uk/articles/accessible-jquery-toggles.htm

    Anyway, I really like your tutorial, and your web design is fantastic. Keep up the good work.

  201. Ike

    I like this allot, I just ran into one snag. The gray backgrounds to the rollovers. When I was looking at it offline I lost those gifs and don’t know how to add them back in. Right now everything else works but I have too mouse over to see the text.

  202. Jules

    First of all a big thank you! I implemented according to your tut, without a hassle. So far… one little problem bugs me. I use several toggable areas on one site, the problem that comes up is while opening or closing an area. When opening there goes a shift over the whole page, not nice.

    Furthemore when I’m openingone of the lower areas, not the first one, the page always seems to center the first area and the one that I tried to open may even disappear in the lower partsof the browser. See for yourself: http://jul.pirateboard.org/Consulting/Casos_Reales.php

    Cheers for any commentand keep up the good work!!

    J

  203. Darren

    I love jQuery, and I find this is a great tutorial. I keep saying I’m going to include something similar to this on my portfolio website, good job.

    You may also find this to be useful, it is a basic video on jQuery and slideToggle effects jQuery slideToggle Tutorial

  204. Soeren

    THX for this nixe tut!!
    @Jules:to avoid jumping you can add return false. That should fix your problem :)
    $(document).ready(function(){

    //Hide (Collapse) the toggle containers on load
    $(“.toggle_container”).hide();

    //Switch the “Open” and “Close” state per click then slide up/down (depending on open/close state)
    $(“h4.trigger”).click(function(){
    $(this).toggleClass(“active”).next().slideToggle(“slow”);
    return false;});

    });

    Regards
    Soeren

  205. mastanto

    Heheheheeyyy It’s awesome! ^^ Thank you very much.

  206. Flo

    I would be also interested, like George, in a nested solution.
    I would need to toogle various elements in a toogled block, kind of a 2nd toggle level, I hope someone understands my need ;)

  207. Ron

    Had issues with accorden function in IE and switch to this, then it was jumping but i added the

    return false;

    and everything works great in IE7 IE8 and FF !!!

    Thanks

  208. No1

    Hey, actually I am having the problem with my BG container … actually I have a BG container and in which I am using this toggle effect … http://i47.tinypic.com/abrtrp.jpg

    BLah BLah…..

    Speak Now
    <!—->
    Consequat te olim letalis premo ad hos olim odio olim indoles ut venio iusto. Euismod, sagaciter diam neque antehabeo blandit, jumentum transverbero luptatum. Lenis vel diam praemitto molior facilisi facilisi suscipere abico, ludus, at. Wisi suscipere nisl ad capto comis esse, autem genitus. Feugiat immitto ullamcorper hos luptatum gilvus eum. Delenit patria nunc os pneum acsi nulla magna singularis proprius autem exerci accumsan.
    </div

    please help me ….

  209. No1

    Hey, actually I am having the problem with my BG container … actually I have a BG container and in which I am using this toggle effect … http://i47.tinypic.com/abrtrp.jpg

    my problem is I am not getting BG when the toggle is off … so how do i get BG of the whole box ????????
    /************

    Web Design & Development

    OOOOOOOO
    <!—->
    Consequat te olim letalis premo ad hos olim odio olim indoles ut venio iusto. Euismod, sagaciter diam neque antehabeo blandit, jumentum transverbero luptatum. Lenis vel diam praemitto molior facilisi facilisi suscipere abico, ludus, at. Wisi suscipere nisl ad capto comis esse, autem genitus. Feugiat immitto ullamcorper hos luptatum gilvus eum. Delenit patria nunc os pneum acsi nulla magna singularis proprius autem exerci accumsan.

    ***************/

  210. Benjy

    Great, thanks. So easy to implement, understand and modify. Unlike others I’ve seen out there.

  211. Mark Law

    Thanks Soh! awesome tut. I have no idea how to write JavaScript but with the help of your tut I managed to implement this on a Joomla site. There is a Mootools conflict but it doesn’t seem to affect anything. Thanks again :)

  212. Chris Ames

    can someone show how to get teh first trigger to to go back to its not active state after you click for th efirst time from loading please?

    http://www.amese.co.uk/dev/amese1/services.php

  213. chris ames

    i’ve just realised that the slide up and down jumps in ie 7 and 8 if you have transparent backgrounds

  214. Artur Nowak

    Very nice toggle effect, I saw several other implementations with JQuery, this one doesn’t have a common flaw: the toggled part of the screen doesn’t “jump” while toggling, even at very short toggle times (I tried 1ms, 10ms, 100ms…). The toggle effect is always very smooth and looks great. Thanks for good work!

  215. Anil

    Thanks for sharing your demo,
    In this demo i want to open one slide at a time if i click on one slide and then i click on another, the first slide become close and second will open like accordion and when i continuous click on the tab i moves it a bug so please can you fix this issue.

  216. Indra

    very good

    is there any plugin to run the effect like on your demo

    i’m not biginner , but fondation about it

    thanks

  217. Jonathan.B

    Nice one! However, is there a way to fix the ‘jump-off-to-top’ bug?

    You know what I mean. I hope there is!, else I need to look for another script :(… And I want your script Sohhh!!! :p lol
    Keep up the good work, cheers

  218. Nick Scola

    How can I get it to go Up and Down. Not Down and Up? Please help.

  219. Adam

    Would love to see the JS code that controls your code snippet horizontal expansion animations – I always seem to have trouble with the mouseover/mouseout using jQuery…

  220. Taylor

    jonathan b. here is what I did to get around the jump to the top of page problem. In the Href I put this “#test”. It does not matter what you put after the pound sign. Just some word. By doing this the code wants to jump to the #test. The only issue is you did not define a #test somewhere else on the page to jump to. It is working for me just fine. This is a way to overcome the jump to the top.

  221. nikhil

    hey buddy, thanks for sharing such wonderful post. Gr8 work.

  222. Ian

    Not sure if anyone can use this, but it’s a simple fix for the split second you see the toggle while the page loads.

    Apply the CSS { display:none } to .toggle_container as Soh mentioned before, then use noscript for the people with javascript disabled -

    .toggle_container { display:block }

  223. Mike

    $(“h2.trigger”).click(function(){
    $(this).toggleClass(“closed”).next().slideToggle(“medium”);
    return false;
    });

    return false; <—- this is what will fix this jump to the top. the jump to the top is due to the href having the # sign.

    Soh – You're one bad motor scooter kid! Keep it up!

  224. KIETH

    Light-weight, practical and sexy. This website is gorgeous too.

  225. Drnuray

    Thanks. Great tutorial.

  226. Kevin

    Very clean, nice!

  227. Randy

    Dig this super slick toggle. Have applied it on a few sites now. Thanks much.

    Having a small issue – the ‘active’ property isn’t being honored for some reason. I’ve checked over and over my CSS, the script, the html, and I cant figure it out. It’s currently the rock in my shoe. Any help would be grand.

    http://www.voodoobean.com/projects/knox/programs.php

    Thanks again for the stellar work.

    Randy

  228. Diana

    I had successfully installed your toggle effect and all was working perfectly. I continued my page development and one day the [+] and [-] images stopped swapping. I’ve copied and pasted your jquery toggle code and css over and over but the images still won’t swap. I am using jquery-1.4.2.js and jscript.js with my jquery code in it at the top of my javascripts in this page.
    $(document).ready(function(){
    $(“.panel”).hide();
    $(“.trigger”).click(function(){
    $(this).toggleClass(“flip”).next().slideToggle(“slow”);
    });
    });
    I changed “active” to “flip” because I was already using and active class elsewhere. But using “active” didn’t work either. Panel is the class name of my hidden content div.
    Any suggestions anyone?!

  229. sekhar

    HI ,
    Wow What a Wonderful design.
    Thanks for great tutorials.
    is there any way to get the images you used for this demo.
    examples images ‘toggle_block_btm.gif’ etc..

    Thanks,

  230. David

    Love the tutorials here, thanks. I’ve adapted this to a “continue reading” button at the bottom of a paragraph that shows the rest of the text when clicked. I’m trying to get the trigger link to slide down with the hidden content so it stays at the bottom rather than in between the visible and newly visible blocks of text.

    When I just put the trigger line after the toggle_container div in my code, it toggles the state of the button but does not reveal the hidden div.

    I tried messing with the script and if I remove the “.next()” from the slideToggle line, it works but that kills the toggleClass function. Obviously, I have no idea what I’m doing, just muddling along here. Can anyone help with how to do this? Thanks.

  231. Gabe

    Worked like a charm! So simple, yet effective.
    Thanks a bunch bro, bookmarked this page.

  232. Nitin Deepak

    Dropdown panel script is too gud. Thanks

    I need to learn jquery for sure. Can u Please suggest me the right track to learn jquery.

    Thanks for everything

Speak Your Mind...

Post HTMLNeed to Post HTML Code? Use Postable to post code friendly html. *Wrap all html code in <pre></pre> tags.
Post HTMLNeed to Keep Updated with Comments? Subscribe to comments now.

CSS Gallery