HOWTO: Toggle DIV visibility
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:
<?php
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();
});
});
}<?php
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>'
);
?>
slideToggle is very slow when the <div> contents are huge
Hello Friend,
That was a good example. But this slideToggle effect is very slow when the 's content is huge. For example, I've a DataGrid with 500 rows inside a . When I click a button to toggle, it takes 2 to 4 seconds to toggle one way. But at the same time, when there are around 50 to 80 rows, it is fast (less than a second). What might be the reason behind this? Is it a bug?
Super Cheers,
achu