views:

423

answers:

2

I'm trying to create an endless slideshow of images that does as follows:

  1. Slides the images across a window
  2. When the last image is reached, it begins from the start of the images

Here is my current code:

var direction = '-';

function doScroll()
{
   $('#products ul').animate({left: direction + '500'}, 5000, function()
   {
      if (direction == '-')
      {
          $('#products li:first').before($('#products li:last'));
      }
      else
      {
         $('#products li:last').after($('#products li:first'));
      }
   });
}

$(document).ready(function()
{
   $('#products ul').css({'width': $('#products ul li').length * 185});

   plzscroll = setInterval("doScroll()", 1000);
}); 

The reason for setInterval() is to create an endless animation.

According to Firebug, the UL get scrolled 500px to the left and then stops... The LI's successfully get moved around, however. The first image gets placed at the end of the slideshow and continues on.

All I need is to figure out why the animation doesn't continue sliding UL.

+2  A: 

I can't setup a test case at the moment, but since you're animation is set to take 5 seconds, but the interval is triggered after 1 second, moving the elements around probably preempts the next animation. Also, you probably want a -=500 for your left, so it continues to go left instead of going to -500 every time.

Try this:

var direction = '-=';
function doScroll()
{
   $('#products ul').animate({left: direction + '500'}, 5000, function()
   {
      if (direction == '-=')
      {
          $('#products li:first').before($('#products li:last'));
      }
      else
      {
         $('#products li:last').after($('#products li:first'));
      }
      setTimeout(doScroll, 1000);
   });
}

$(function()
{
   $('#products ul').css({'width': $('#products ul li').length * 185});
   setTimeout(doScroll, 1000);
}); 

This triggers the next animation 1 second after this animation finishes, hopefully that's something like what you're after.

Side note: Try not to use eval() This is what passing a string to setTimeout() or setInterval() does, pass a function or anonymous function instead like I have above.

Nick Craver
A: 

It is unusal that you are modifying the dom in your animation with before() and after(). I would try to rewrite the method so that the only thing that changes is the position of the #products ul element. Note that to maintain the smooth scrolling effect you would have to duplicate the first and last elements in your list. Or are the images being loaded dynamically?

CurtainDog