Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 571
Kyle Yeo Avatar asked Apr 05 '12 16:04

Kyle Yeo


People also ask

What is fadeIn and fadeOut in jQuery?

The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods. If the elements are faded out, fadeToggle() will fade them in. If the elements are faded in, fadeToggle() will fade them out. Syntax: $(selector).

What is fadeOut in jQuery?

jQuery Effect fadeOut() Method The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.

What is the syntax of jQuery fadeIn () method?

jQuery fadeIn() Method The fadeIn() method gradually changes the opacity, for selected elements, from hidden to visible (fading effect).

What is the difference between fadeOut and hide in jQuery?

fadeOut() the place will be removed at once. . show(duration) and . hide(duration) animate the size of element (also the opacity) to 100% and 0% and the place of elements is also animated in that duration.


1 Answers

(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/

like image 110
Yoshi Avatar answered Oct 20 '22 01:10

Yoshi