Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery cross fading two images on a loop!

I am having trouble working out how to get a simple fade in fade out loop to work. I am pretty new to jQuery as you can maybe tell. I have had a go at it but now it’s taking too long to work out so I thought I would ask for some help.

What I want to do:

I have two Images, id's #img1 and #img2. I want image 1 to fadeIn then wait for lets say 6 seconds then fade out. I have tried the .wait function but it just stopped the little I had from working. I managed to get the first image to fade in and then out but with no wait in between. I then want to start fading image 2 in while image 1 is fading out then Image 2 to wait then fade out while image 1 fades in again and loop forever! Hope that makes sense.

 $(document).ready(function(){
  $('#img1').hide()
.load(function () {
  $(this).fadeIn(4500)
  .fadeOut(4500);
  $('#img2').hide().wait(9000)
  .load(function () {
  $(this).fadeIn(4500)
  .fadeOut(4500);
});

Cheers, its driving me crazy. Ps can you try and give a little explanation to what is going on in you answer. Thanks

like image 640
Cool Hand Luke Avatar asked Sep 06 '09 18:09

Cool Hand Luke


2 Answers

Here's a four image looping slideshow that does not use the setTimeout function, but instead uses the delay function.

<script>
  function startSlideshow(){
    $("div.text_b1").fadeIn(1000).delay(10500).fadeOut(1500); //13000
    $("div.text_b2").delay(13000).fadeIn(1500).delay(11000).fadeOut(1500); //27000
    $("div.text_b3").delay(27000).fadeIn(1500).delay(11000).fadeOut(1500); //41000
    $("div.text_b4").delay(41000).fadeIn(1500).delay(11000).fadeOut(1500, startSlideshow); //55000
  }

  $(document).ready(function(){
    startSlideshow();
  });
</script>

see it in action http://www.erestaurantwebsites.com/

like image 137
Ted Avatar answered Sep 17 '22 12:09

Ted


Why don't you use a solution already made like the Cycle plugin?

It has a lot more of options than you want to do.

If you really need to do this by yourself you could watch at the source code of the plugin. I didn't do that, but I think the coder uses a combination of the animate function (from jQuery) and the setTimeout function (from purely javascript). Using those functions he must do something like to enable a timer for an amount of time, and when time's complete he execute the animate function setting the opacity of the image to 0 (for the image hidding) and 1 (for the image showing).

like image 41
eKek0 Avatar answered Sep 18 '22 12:09

eKek0