Painless Collapsible Divs In Drupal

It's almost midnight in my area, but I couldn't resist sharing this cool theming tip with you. Ok, so you want to create a cool collapsible div to hide some content on your page. What would you do? Write another javascript/jquery snippet and mess with callbacks, toggles, etc?

Well, in Drupal this can be done even easier! Chaos tool suite (aka Ctools) comes to rescue! This module is a must have on any website, so don't worry about installing one more module to do a simple thing. And I'm 90% of you have it already installed.

Ok now to the process, let's collapse the div!

1) Put the content you want to see in a collapse field into the variable, let's call it $collapsed_content
2) And now the magic comes, use this theme function to output collapsible div:

print theme('ctools_collapsible', array('handle' => 'Click me and you will see collapsed content', 'content' => $collapsed_content, 'collapsed' => TRUE));

handle - stands for a clickable text which will collapse/uncollapse your div;
content - we put out content here, previously assigned to $collapsed_content variable;
collapsed - defines default state of a collapsible div, in our case it's collapsed, if FALSE it's uncollapsed. Simple.

That's all! Just two lines of code and you're set with a nice collapsible div.

Note for novices: you can put this code to your node template (for example, node.tpl.php file) OR to your custom module (custom_module.module file) OR to template.php file, on overall, to any place where you have a code which is responsible for the desired output. If you put this code into your custom module, don't forget to add ctools dependency to your custom_module.info file or otherwise, your site may break if you accidentally uninstalled ctools.

Comments

Submitted by Benjamin Lutaaya on Wed, 12/21/2011 - 09:58

Thanks for sharing

Submitted by felix on Sat, 02/11/2012 - 11:16

Thanks for this. I am a noob, it's true, but thanks to your advice I got it working....only I had to put my variable ($collapsed_content) into my custom node--17.tpl.php - If I added it as a PHP Code wrapped variable in the normal way I add text to a page, it gives the 'undefined variable' error....
I would prefer to be able to update my content without editing tpl.php files, is there a way to declare teh variable's value through the standard content-adding Drupal mechanisms?
Also,as the page renders, you see the collapsed text for half a second before it hides...anyway around that?

Submitted by LK7889 on Wed, 03/07/2012 - 21:35

Thank you! I was looking for an easy way to collapse my comments area div and this did the trick for me after hours of searching for a good, Drupalized way to complete this. Your articles have been a major help to me more than once.

Add new comment

You are here