Change javascript to fade in over the top of each other instead of fadein/fadeout?

Below is the javascript in place for a set of images to fade in and out. It works fine and well, but I now want the images to fade in over the top of each-other instead and after playing around I am having some troubles with it.

Javascript:

$(document).ready(function () {


  var $backgroundimages = ['http://www.universitycompare.com/wp-content/themes/blue-and-grey/images/home-test.jpg', 'http://www.universitycompare.com/wp-content/themes/blue-and-grey/images/qanda-front.jpg', 'http://www.universitycompare.com/wp-content/themes/blue-and-grey/images/home-page-slide.jpg', 'http://www.universitycompare.com/wp-content/themes/blue-and-grey/images/TCE-New.jpg'];
  var $backgroundcount = 0;


  function fade($ele) {
    $ele.css('background-image', 'url('+$backgroundimages[$backgroundcount]+')');
    $backgroundcount++;
    $ele.fadeIn(1000).delay(5000).fadeOut(1000, function () {
        if ($backgroundcount >= $backgroundimages.length) {
            $backgroundcount = 0;
        };
        fade($ele);
    });
  };


  fade($('#stretchParent .HomeImage').first());
});

CSS:

    div#stretchParent{width:100%;min-width:960px;height:275px;}
    div.HomeImage{min-width:960px;width:100%;background-position:center !important;background-repeat:no-repeat !important;background-size:cover !important;min-height:275px;position:absolute;top:0;left:0px;margin:125px -0px 0px 0px;display:none;}

For a working version of the above slider, you can also see: http://universitycompare.com


solution

It would be easiest to create an element for each image and then fade the elements while manipulating the z-index at the same time.

SEE THE EXAMPLE HERE

Since you’re already using jQuery, just use .each() to iterate through the array and append the elements to the container element, #stretchParent.

$.each(backgroundImages, function (index, value) {
  $('#stretchParent').append('<div class="HomeImage" style="background-image:url(' + value + ');"></div>');
});

As for the function itself, i’d suggest using setInterval. Set the delay to whatever you want.

setInterval(function () {
  el = $('#stretchParent .HomeImage');
  el.first().css('z-index', 2).fadeOut(1000).appendTo($('#stretchParent'));
  el.eq(1).show().css('z-index', 1);
}, 3000);

The function increases the z-index of the first element and then fades it out and appends it to the end of the container element. The next line simply makes the next element visible while decreasing its z-index to ensure that it will appear behind the current image.

EXAMPLE HERE // FULL SCREEN EXAMPLE HERE