0

i have a div for which i want to show multiple images in the background as a fade in fade out by changing the css background image am unable to find the best way.

JSFiddle

My HTML:

<div id="background"></div>

Jquery

var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "images/TopImage-03.jpg"];
var i = 0;

// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)

function swapBkgnd() {
  if (i > (bgArr.length - 1)) {
    i = 0
    $("#background").css("background-image", "url(" + bgArr[i] + ")");
  } else {
    $("#background").css("background-image", "url(" + bgArr[i] + ")");
  }
  i++;
};

CSS:

#background {
  position: absolute;
  min-height: 100%;
  width: 100%;
  height: auto;
  top: 0;
  left: 0;
  background: url(http://2.bp.blogspot.com/-ayEwJpMGTPQ/USqliwPWo1I/AAAAAAAAHtI/ab6NHVy0Q48/s1600/tree.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
Shaik
  • 930
  • 1
  • 20
  • 48

3 Answers3

3

Use:

Jsfiddle: http://jsfiddle.net/ook3ah4p/

var interval = self.setInterval(swapBkgnd, 5000) // true syntax

instead of:

var interval = self.setInterval("swapBkgnd()", 5000) // wrong syntax

for animation:

$('#background')
    .animate({opacity: 0}, 'slow', function() {
        $(this)
            .css({'background-image': "url(" + bgArr[i] + ")"})
            .animate({opacity: 1});
    });
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
0

Set it up like this:

function swapBkgnd() {
  if (i > (bgArr.length - 1)) {
    i = 0;
  }
  $("#background").fadeOut("slow", function () {
    $(this).css("background-image", "url(" + bgArr[i] + ")");
    $(this).fadeIn("slow");
  });
  i++;
};
Gerard
  • 15,418
  • 5
  • 30
  • 52
0

Refering to this answer How to fade changing background image

var interval = self.setInterval(swapBkgnd, 5000)

function swapBkgnd() {
    if (i > (bgArr.length - 1)) {
        i = 0
        $('#background').fadeTo('slow', 0.3, function(){
            $(this).css('background-image', 'url(' + bgArr[i] + ')');
        }).fadeTo('slow', 1);
    } else {
        $('#background').fadeTo('slow', 0.3, function(){
            $(this).css('background-image', 'url(' + bgArr[i] + ')');
        }).fadeTo('slow', 1);
}
i++;
};
Community
  • 1
  • 1
Sanooj T
  • 1,317
  • 1
  • 14
  • 25