Shaik Shaik - 7 months ago 54
Javascript Question

Change Background image url of div

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;
}

Answer

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});
    });
Comments