user279860 user279860 - 1 year ago 67
CSS Question

jQuery toggling divs, expand collapse all and keep first item selected when page loads

I have a question about some functionality I'm trying to add to my jQuery to enable a button or text to expand/contract all the divs on click... and I'd like to figure out how to keep the first div open when the page loads.

Here is the jQuery:


//Hides containers on load

//Switch "Open" and "Close" state on click
}, function () {

//Slide up and down on click

And the css:

// uses a background image with an on (+) and off (-) state stacked on top of each other
h2.trigger { background: url(buttonBG.gif) no-repeat;height: 46px;line-height: 46px;width: 300px;font-size: 2em;font-weight: normal;}
h2.trigger a {color: #fff;text-decoration: none; display: block;} {background-position: left bottom;}
.toggle_container { overflow: hidden; }
.toggle_container .block {padding: 20px;}

And the html

<h2 class="trigger"><a href="#">Heading</a></h2>
<div class="toggle_container">
<div class="block">Stuff goes here</div>

<h2 class="trigger"><a href="#">Heading 2</a></h2>
<div class="toggle_container">
<div class="block">Stuff goes here</div>

So it works great and looks great. However, when I try to get it to keep the first instance open, the background image that should adjust show the (-) state doesn't change. The code I used to this was:


So, my question is, does anyone know of an easier way to show the first instance of this as open without having to created specials rules/class for the first item? Also, any ideas about how to make an open all/close all link?


Answer Source

You can change all your jQuery to this:



This hides all but the first .toggle_container, applies the class="active" to it's matching <h2>, and the toggle() is just simpler, a click now toggles the we can just add active to match it being open on page load and it'll behave correctly.

Also, a open/close all would look like this:

<a href="#" id="openCloseAll">Open All</a>

jQuery like this:

$("#openCloseAll").toggle(function() {
  $(this).text("Close All");
}, function() {
  $(this).text("Open All");

This opens all closed on the first click, changes it's text to accurately describe what the next click will do, and closes all open on the next click, then switches back, rinse, repeat.