Saturday, 13 September 2008

JavaScript image changer

I'm definitely not a JavaScript programmer. I just wanted to have a simple script that would change background image on the site automatically in a loop. I couldn't find a ready ouf-of-the-box solution so I've created my own. It's based on YUI. The only reason of choosing YUI over Prototype or JQuery was that YUI it's used by LightFlow. The target site of my image loop changer was already using LightFlow so JavaScript could be shared.

Here is my code. This code is definitely not mature but still maybe you'll find it helpful. The following things should be applied to your HTML:

1. Load the YUI library
<script type="text/javascript"
src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js">
</script>

2. Create a DIV with the original image background (the one loaded initially)
<div id="imageLoopDiv" style="background: url(img1.jpg) no-repeat;">

3. Initialize JavaScript: provide the list of images (loopImages), pre-load the images so that they don't blink when changed, and register the function that automatically switches backgrounds
<script type="text/javascript">

var loopImages=new Array('img1.jpg','img2.jpg','img3.jpg');

var showNextImage=function(){
var currentImage=YAHOO.util.Dom.getStyle('imageLoopDiv','background');
var currentIdx=0;
for(var i=0;i<loopImages.length;i++)
if(currentImage.indexOf(loopImages[i])!=-1){currentIdx=i; break;}
var newImage=loopImages[(currentIdx+1)%loopImages.length];
YAHOO.util.Dom.setStyle('imageLoopDiv','background','url('+newImage+') no-repeat');
};

YAHOO.util.Event.addListener(window,'load',function(){
for(var i=0;i<loopImages.length;i++){
var img=new Image(); img.src='../img/'+loopImages[i];
}
YAHOO.lang.later(10000,null,showNextImage(),null,true);
});

</script>

The running example of this scipt is oodesign.eu. This scripts are script.js and yui-utilities.js.

1 comment:

yogesh kumar said...

This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
WordPress development company in Chennai