PHP / MooTools 1.2 Accordion Helper

By  on  

The MooTools Accordion plugin seems to be the plugin that people seem to have the most problems with. It's an awesome plugin, so I can see why so many people want to use it, but I think that may be part of the problem. I think people see and want it without sufficient knowledge of MooTools or JavaScript in general. That's why I've created a PHP Accordion class to help make the development of accordions easier and faster.

The PHP Class

class accordion
{
	var $toggler_class;
	var $item_class;
	var $items;
	var $open;
	
	function accordion($toggler_class = 'toggler',$item_class = 'item')
	{
		$this->items = array();
		$this->toggler_class = $toggler_class;
		$this->item_class = $item_class;
		$this->open = 0;
	}
	
	function add_item($toggler_content = '',$item_content = '',$open = 0)
	{
		$this->items[] = array('toggler'=>$toggler_content,'item'=>$item_content,'open'=>(int)$open);
	}
	
	function build()
	{
		foreach($this->items as $index=>$item)
		{
			$return.= '
'.$item['toggler'].'
'.$item['item'].'
'; if($item['open']) { $this->open = $index; } } return $return; } function output() { echo $this->build(); } function output_js($options = '') { return 'window.addEvent(\'domready\', function () { var accordion = new Accordion($$(\'.'.$this->toggler_class.'\'),$$(\'.'.$this->item_class.'\'), { display:'.$this->open.' '.($options ? ', '.$options : '').' }); });'; } }

Check out the usage for comments about the class.

The PHP Usage

$acc = new accordion('toggler','item');

$acc->add_item('The Beatles','<img src="https://davidwalsh.name/demo/accordion/let-it-be.jpg" class="image" />
<p>The Beatles were a pop and rock group from Liverpool, England. They are one of the most commercially successful and critically acclaimed bands in the history of popular music. The band\'s principal members were John Lennon, Paul McCartney, George Harrison, and Ringo Starr.</p>
<p>The Beatles led the mid-1960s musical "British Invasion" into the United States. Although their initial musical style was rooted in 1950s rock and roll and homegrown skiffle, the group explored genres ranging from Tin Pan Alley to psychedelic rock. Their clothes, styles, and statements made them trend-setters, while their growing social awareness saw their influence extend into the social and cultural revolutions of the 1960s.</p>
<p><a href="http://en.wikipedia.org/wiki/The_beatles">Click here</a> to learn more about The Beatles.</p>');

$acc->add_item('Rod Stewart','<img src="https://davidwalsh.name/demo/accordion/every-picture.jpg" class="image" />
<p>Roderick "Rod" David Stewart, CBE (born January 10, 1945), is a singer and songwriter born and raised in London, England, with Scottish and English parentage. He currently resides in Epping. With a distinctive, raspy voice, Stewart came to prominence in the late 1960s and early \'70s with The Jeff Beck Group and then The Faces and began a solo career in 1969, with his debut album An Old Raincoat Won\'t Ever Let You Down.</p>
<p>With his career in its fifth decade, Stewart has achieved numerous hit singles worldwide, most notably in the UK, where he has garnered six consecutive number one albums and his tally of 62 hit singles include 24 that reached the top 10, six of which gained the number one position. It has been estimated that Stewart\'s album and single sales total more than 250 million, easily earning him a place on the list of best-selling music artists.</p>
<p><a href="http://en.wikipedia.org/wiki/Rod_Stewart">Click here</a> to learn more about Rod Stewart.</p>', 1);

$acc->add_item('Oasis','<img src="https://davidwalsh.name/demo/accordion/oasis.jpg" class="image" />
<p>Oasis are an English rock band that formed in Manchester in 1991. The group was formed by Liam Gallagher (lead vocals), Paul Arthurs (guitar), Paul McGuigan (bass) and Tony McCarroll (drums), who were soon joined by Liam\'s older brother Noel Gallagher (lead guitar, vocals). Oasis have sold more than 50 million albums worldwide, and have had eight UK number one singles. The Gallagher brothers are the band\'s leading songwriters and the only continual members. The present lineup is completed by rhythm/lead guitarist and songwriter Gem Archer, guitarist and songwriter Andy Bell and as-yet unofficial drummer Zak Starkey.</p>
<p><a href="http://en.wikipedia.org/wiki/Oasis_band">Click here</a> to learn more about Oasis.</p>');

echo $acc->output(),'<script type="text/javascript">',$acc->output_js(),'</script>';

When creating the accordion, pass in the CSS class given to each toggler element and the CSS class given to each content element. Then it's time to add accordion items. For each item you want to create, pass in the toggler's content, the item's content, and whether you'd like the given item to start open. Once all of the items are in, you can call output() to output the XHTML and output_js() to output the MooTools JavaScript. You can pass extra options to output_js() if you'd like to get fancy.

If you already know how to create a MooTools accordion, I'm not sure that this class would be of any value to you. If, however, you've been struggling with creating one, this may be that little helper that gets you there.

Recent Features

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Select Dropdowns, MooTools, and CSS Print

    I know I've harped on this over and over again but it's important to enhance pages for print. You can do some things using simple CSS but today's post features MooTools and jQuery. We'll be taking the options of a SELECT element and generating...

  • By
    Dynamic Waveform Visualizations with wavesurfer.js

    Waveform images are an awesome addition to boring audio widgets.  They can be functional as well as aesthetically pleasing, allowing users to navigate audio visually.  I recently found wavesurfer.js, an amazing waveform image utility that uses to Web Audio API to create super customizable...

Discussion

  1. Devil

    Hi, works this with mootools 1.1x ?

    greetings Devil

  2. @Devil: This PHP helper will not work with Moo 1.1.

  3. Rotemweb

    Hi. Thanks for your work. Is there any possibility to make these accordions horizontal? (still with mootools 1.2 of course). Thanks

  4. I also am looking for a horizontal accordion mootools example. Even better if it could work to do the slide of one button like this non-moo example, http://www.dynamicdrive.com/dynamicindex17/featuredcontentslider.htm. Thanks.

  5. vbnccvbvbnvbcnvbnvbn

  6. Bellir

    Hi
    My question is not about the accordion plug in but about this “post comment” feature. Could you so kindly tell me where I can get code for this?
    tks
    Bellir

  7. riseryn

    hi,
    when i try to use your example i got Undefined property: accordion::$add_item.
    Any idea why?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!