First example

Toggling DIVs in some way or another (visibility especially) is a common practice nowadays, especially with Ajax-enabled applications. And since Drupal happily supports Ajax, why not spice up your modules with a little DIV toggling? Do be careful not to overdo it, though!

Desired HTML:

<div class="toggle_area">
  <div class="toggle_label">Description</div>
  <div class="toggle_content">Content:
     Some content here...
  </div>
</div>

jQuery code in the file foobar.js:

if (Drupal.jsEnabled) {
  $(document).ready(function () {
    $('div.toggle_area').find('div.toggle_content').hide().end().find('div.toggle_label').click(function() {
      $(this).next().slideToggle(); 
    });
  });
}

And some sample module code:

drupal_add_js('foobar.js');

$form['foobar_A'] = array(
  '#prefix' => '<div class="toggle_area"><div class="toggle_label">Descriptive Label</div><div class="toggle_content">',
);
$form['foobar_B'] = array(
  '#suffix' => '</div></div>'
);

The jQuery code, together with properly placed DIVs in #prefix and #suffix allows for slide-able form elements.

Second example

There is one major drawback of using DIVs for toggling slide-able elements: when you process your form you cannot tell if that region should be processed (if it is hidden, it still contains all of the data that may have been entered in it). You can try wrapping the DIV around a checkbox, but then the whole region of the DIV (not just the checkbox) is the toggle switch. To restrict the area to just the checkbox element, you can modify the code above to:

Desired HTML:

<div class="toggle_area">
  <div class="toggle_label">Description</div>
  <div class="toggle_content">Content:
     Some content here...
  </div>
</div>

jQuery code in the file foobar.js:

if (Drupal.jsEnabled) {
  $(document).ready(function () {
    $('div.toggle_area').find('div.toggle_content').hide().end().find('input:checkbox').click(function() {
      $(this).parents().children(div.toggle_content').slideToggle();  
    });
  });
}
drupal_add_js('foobar.js');

$form['foobar_A'] = array(
  '#type' => 'checkbox',
  '#prefix' => '<div class="toggle_area">',
  '#suffix' => '<div class="toggle_content">',
);
$form['foobar_B'] = array(
  '#suffix' => '</div></div>'
);

Comments

dobrzyns’s picture

I've noticed all sorts of approaches to having multiple divs that toggle independently on a page when searching the internet. What is the best-practice way to do this in Drupal?

legolas_001’s picture

how to to this when there is multiple divs and i want to keep first item collapsed by default?!

tutumlum’s picture

http://drupal.org/node/1037322 it worked well for me