Interweaving background images using jQuery fadeIn () and fadeOut ()

I am using the following function to create a slideshow of images with fade on and off effects.

var project_photos = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var project_photo_index = 0;

function nextPhoto() {
  $('#background').fadeOut();
  $('#background').css('background-image', 
    "url('images/" + project_photos[project_photo_index] + "')");
  $('#background').fadeIn();
  timer = setTimeout(function() {
    if (project_photo_index+1 > project_photos.length) {
      project_photo_index = 0;
    } else {
      project_photo_index++;
    }
    nextPhoto();
  }, 5000);
}

      

However, I want to tweak the function a bit to remove the white points between fadeOut()

and fadeIn()

. I want to achieve:

assuming the fade-out time is 400ms and the display time of each image is 5s

  • Image 1 shows on screen from 0 to 5 seconds, starts to fade from 5 to 5.4s
  • Image 2 first disappears, starts to fade from 4.8 to 5.2s (to fill the white gap between fade and fallout), holds from 5.2 to 10.2s, then starts to fade from 10.2 to 10.6s
  • Image 3 first disappears, begins to fade from 10.4 to 10.8 s, from 10.8 to 15.8 s, then begins to fade from 15.8 to 16.2 s.
  • (and image 1 returns with similar logic, loops forever until the timer clears)

How do I configure the code to work as described?

+1


source to share


2 answers


LIVE DEMO

If you are using 2 DIV elements you can blank out the inner one:

<div id="bg2"><div id="bg1"></div></div>

      

than this is all you need:



var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'],
    n = images.length,
    c = 0,
    $1 = $('#bg1'),
    $2 = $('#bg2');

$.fn.setBG = function(){
  return this.css({backgroundImage: "url(images/"+ images[c] +")"});
};

(function loop(){
  $1.setBG().fadeTo(0,1).delay(2000).fadeTo(1000, 0, loop);
  c = ++c%n;
  $2.setBG();
})();

      

How it works:

#bg1:      set1 -- fadeOut -- set2 -- fadeOut -- set3 -- fadeOut -- set1 - ...
#bg2:      - set2 ------------- set3 ------------- set1 ------------- set2 ...

      

+2


source


Try something like

var project_photos = ['//placehold.it/128/ff0000', '//placehold.it/128/ffff00', '//placehold.it/128/00ff00', '//placehold.it/128/00ffff'];
var project_photo_index = 0;

//preload the images
$.each(project_photos, function (i, src) {
    var img = $('<img />', {
        src: src
    })
})

function nextPhoto() {
    $('#background').fadeTo('normal', .5, function () {
        $(this).css('background-image', "url('" + project_photos[project_photo_index] + "')")
        $(this).fadeTo('normal', 1)
    });

    project_photo_index++;
    project_photo_index = project_photo_index < project_photos.length ? project_photo_index : 0;

    setTimeout(nextPhoto, 5000)
}

nextPhoto();

      



Demo: Fiddle

+1


source







All Articles