invidious
invidious

Reputation: 241

jQuery slowly fade in and out, pause, and then repeat

I have 4 images in a list that I would like to slowly fade out, then in, then move on to the next, and repeat until it comes back to the time. So I basically need to use this code, but have it pause until the other 3 are complete, then do it again.

How can I go about doing that?

$('#image1').animate({ opacity: 1/3 }, 500);
$('#image1').animate({ opacity: 1 }, 1000);
$('#image2').animate({ opacity: 1/3 }, 2000);
$('#image2').animate({ opacity: 1 }, 2500);
$('#image3').animate({ opacity: 1/3 }, 3500);
$('#image3').animate({ opacity: 1 }, 4000);
$('#image4').animate({ opacity: 1/3 }, 5000);
$('#image4').animate({ opacity: 1 }, 5500);

How do I loop it? Is this the best way to do it?

Upvotes: 1

Views: 272

Answers (3)

renakre
renakre

Reputation: 8291

How about this:

var speed = 2000;
run = setInterval("switchSlide()", speed);
$(document).ready(function() {

  $('#caption').html($('#slideshow img:first').attr('title'));

  $('#slideshow img:gt(0)').hide();
});

function switchSlide() {
  $('#slideshow img:first').fadeOut(1000).next().show().end().appendTo('#slideshow');
  $('#caption').html($('#slideshow img:first').attr('title'));
}
#slideshow {
  width: 700px;
  height: 400px;
  padding: 0;
  position: relative;
  overflow: hidden;
  border: 1px solid;
}
#slideshow img {
  position: absolute;
  height: 500px;
  width: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slideshow">
  <img src="http://icons.iconarchive.com/icons/fasticon/nature/256/Pink-Flower-icon.png" title="test1" />
  <img src="http://icons.iconarchive.com/icons/fasticon/nature/256/Blue-Flower-icon.png" title="test2" />
  <img src="http://icons.iconarchive.com/icons/fasticon/nature/256/Red-Flower-icon.png" title="test3" />
</div>

ADAPTED FROM: https://stackoverflow.com/a/14875852/1845408

Upvotes: 1

artm
artm

Reputation: 8584

See http://jsfiddle.net/8uysuv3q/

$(".fade").each(function(index) {
    $(this).delay(800*index).fadeTo(200, 0.5).fadeTo(200, 1).fadeTo(200, 0.5).fadeTo(200, 1);
});

Upvotes: 2

mlrawlings
mlrawlings

Reputation: 741

function fadeInOutList($elements, duration, delay) {
     if(!$elements.size()) return
     
     $elements.first().fadeIn(duration, function() {
       setTimeout(function() {
          $elements.first().fadeOut(duration, function() {
             fadeInOutList($elements.slice(1), duration, delay)
          })
       }, delay)
     })
}


fadeInOutList($('img'), 500, 1000)
img {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://vk.com/images/gifts/256/71.jpg" />
<img src="http://images.math.cnrs.fr/IMG/png/section8-image.png" />
<img src="http://vk.com/images/gifts/256/44.jpg" />
<img src="http://breckon.eu/toby/fundipbook/materials/gallery/cameraman.jpg" />

Upvotes: 1

Related Questions