views:

287

answers:

2

The issue I am having is fairly complicated to explain. I have written up a javascript that displays an image slideshow, and it works fairly well, despite using up more resources than I would like

// imgArr[] is populated before    
var i = 0;
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}

function loaded(i,f) {
if (document.getElementById(i) != null) f();
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}

}

function displaySlideshow() {
  document.getElementById(destinationId).innerHTML = '<div id="slideWindow"><img src="'+imgArr[i]+'" />'  +  '<img src="'+imgArr[i + 1]+'" /></div>';
  setTimeout('displaySlideshow()',1000*3);
  i++;
  if (i >= imgArr.length - 1)
     i = 0;
}
loaded(destinationId,displaySlideshow);

So, this script dynamically adds two images to a HTML element, and it is wrapped in a div.

The div is styled with the height and width of the image, with the overflow (the second image) hidden. The second image is below the first, and the slideshow is meant to go from RIGHT to LEFT.

My inquiry is twofold: 1) Is there a more efficient way of doing this? 2) How would I animate the images? Would I need to put the second image on the right of the first with CSS somehow, and then set a timer to pull the images (via a style) leftward?

A: 

I really don't recommend rolling your own animation library. The Facebook Animation Library written by the wonderful Marcel Laverdet is simple to use and comes with a lot of tutorials to get what you want out of your slideshow. (Note: ignore the FBJS stuff, it's exactly the same even if you're using it on your own site.)

jonchang
I don't want to incorporate a library for a small animation. Not to mention, the whole reason I am doing this without a library is so I can learn the fundamentals.
aaron
It's really painful. It'd be a lot better to examine the code involved in the Animation library, and then try to duplicate the functionality in your own code.
jonchang
A: 

If you're not using a framework, I think you'll find a lot of pain ahead of you. If you still don't want to use a framework, at least find one that is liberally licensed, and take a look at the source code. Here's one, for example.

The basic theory is, yes, you set a timer that moves the image on some sort of interval, either fixed or based on some sort of mathematical equation (eg, sin, cos, etc). By setting these intervals close together, and making lots of them, you get an "animation" in javascript. Typically, you'd use some sort of absolute positioning, moving one element off the screen as the other moves on.

jvenema