Extending Javascript Crossfading Effect

Sep
25
2006

While I like scriptaculous, sometimes you just want to cycle through messages and fade between them and don't need a full-blown effects library. A script popped up in the feeds today that does just that.

It intrigued me because I'd been looking at something like this to be able to easily and programatically whip up intros for screencasts. Simply write up some slides, turn on the screencam, run this and you've got your intro video ready to go. Same with credits. Basically, I want to streamline those bits of production and lower the barrier to me producing screencasts.

The library itself can be found at Brand Spanking New. It comes with a sample page and sample code to invoke it, but I thought I'd share a really quick way to extend it.

The sample invocation looks like this:

var cf = new Crossfader( new Array('cf1','cf2','cf3'), 500, 2000 );

The "cf1", "cf2", etc. are the divs to cycle between and the numbers are how long the fades take and how long the individual slides take (in milliseconds).

That immediately struck me as a pain because it requires you to manually add new "slides" to the array, in addition to actually putting them into the HTML document.

This snippet below uses the same HTML document in the sample. It grabs the containing div and then grabs all child divs with a class name of "cf_element" and adds them to the cycle.

var container = document.getElementById("cf_wrapper")
var children = container.getElementsByTagName("div");
var cycled_elements = new Array();
for ($i=0;$i<children.length;$i++){
     if(children[$i].className == "cf_element"){
         cycled_elements.push(children[$i].id);
      }
}
var cf = new Crossfader( cycled_elements, 500, 2000 );

This isn't terribly efficient and should really be fixed up, but that's not in the scope of a quick tip. However, if you were to take that task on, I'd suggest making a single function that takes an id as input. All of the immediate child elements (regardless of div or img or whatever) would be added to the cycle, regardless of class name.

 

Comments on this post

Feedback is always welcome. Read some from other folks or leave your own below. Just keep things civil and remember that what you post lives on in public. Forever.

Thanks,
J

Leave Your Own Comment

By submitting a comment, you agree to license it under the terms of the Creative Commons Attribution license.

© 2003-2008 J Wynia. All original content is licensed under the terms of the Creative Commons Attribution license unless otherwise noted. Content from other sources is licensed under its original terms.