Make sidebar blocks collapsible

Last modified: October 18, 2008 - 04:01

Thought I'd share this:
Here's how I made the Block Div's hidable using javascript (and scriptaculous.js). Put it somewhere in the page, or in a separate file, that gets included in the page..

<?php
<script language="javascript" type="text/javascript">
// make blocks collapse by clicking on title.
blocks=document.getElementsByTagName("div");
blocks=$A(blocks);
blocks.each (
function(
block){
  if (
block.className=='block') {
  
title=block.childNodes[1];
  
title.onclick = function () {
   
content=this.parentNode.childNodes[3];
   
content.style.display!='none' ? content.style.display='none' : content.style.display='block';   
  }
}
}
);
</script>
?>

(To add: some cookie stuff to let the browser remember which blocks you've got hiding/showing.)

Prototype-ish approach to the script; it requires Prototype 1.6.

<script language="javascript" type="text/javascript">
// Assuming jQuery.noConflict is already called.
if (Drupal.jsEnabled) {
$(document).observe('dom:loaded', function() {
$$('div.block h2').invoke('observe', 'click', function() {
  $(this).up().down('div.content').invoke('toggle');
});
});
}
</script>

jQuery approach, which is supposed to work with Drupal 5.

<script language="javascript" type="text/javascript">
if (Drupal.jsEnabled) {
(function($) {
$('div.block h2').click(function() {
  $(this).parent().find('div.content').slideToggle();
});
})(jQuery);
}

More info: See 'Collapsiblock' under jstools module for a full-blown and configurable version of this task. I think it's cookied by now.

jquery example is missing </script>

lucyconnuk - December 1, 2008 - 14:20

jquery example seems to be missing a final </script>

 
 

Drupal is a registered trademark of Dries Buytaert.