jQuery Animation, Chaining, .each() and .animate() (or fadeIn() and fadeOut())

html, javascript, jquery

Solution

(function loop() {
  $('.elements').each(function() {
    var $self = $(this);
    $self.parent().queue(function (n) {
      $self.fadeIn(2000).delay(200).fadeOut(2000, n);
    });
  }).parent().promise().done(loop);
}());

demo: http://jsfiddle.net/uWGVN/2/

updated to have it looping without end.

2nd update: a different, probably more readable, approach:

(function fade(idx) {
  var $elements = $('.elements');
  $elements.eq(idx).fadeIn(2000).delay(200).fadeOut(2000, function () {
    fade(idx + 1 < $elements.length ? idx + 1 : 0);
  });
}(0));

​demo: http://jsfiddle.net/uWGVN/3/

Problem

I'm having a bit of a trouble trying to figure this out today, i want to make 5 items inside my DOM (which is listed under the same attribute element, $('.elements')) fade in and out, and after reading up a bit on the API i thought .each() would be a fabulous idea to implement a fade in and fade out showcase gallery. However, i'm currently using: ``` $('.elements').each(function() { $(this).fadeIn(2000).delay(200).fadeOut(2000).show(); }) ``` but everything gets faded in and out at once. How do i do a sequential effect where everything is chained together and it starts from the first item in the list (a.k.a - $('elements').eq(0)?) down to the last one, and then restarts again? Do i really need a while loop to do this in javascript/jquery? I was hoping there would be a similar function that i could chain for jQuery to perform to reduce load and filesize. Also, is there a way to restrict the images from overflowing out from my div?

Original source