Astrify Astrify - 2 months ago 6
Javascript Question

timed background change for whole body background

I'm trying to have a background change on queue. This is what I have to change the background:

var bgarray = new Array();
var curbg = 0;

function getBackgrounds() {
var totalbg = 4;

for (var i = 0; i < totalbg; i++) {
bgarray[i] = 'url("img/' + i + '.jpeg")';
}
}

function changeBackground() {
debugger;

if (curbg === (bgarray.length - 1)) {
curbg = 0;
}

var bgurl = bgarray[curbg];
curbg++;

$(document.body).animate({
'background-image': bgurl
}, 1000);
}


I've used
setInterval(changeBackground, 5000);
in my calling code, yet it just will not change the background.

The console is not logging any errors and the files definitely exist.

Any idea why there is no change?

Answer

var bgarray = ['https://2.bp.blogspot.com/-AXkkbmFRErs/TjCZIWGawfI/AAAAAAAAAlk/lT8yTGBYh38/s1600/Rick-Roll3.png','http://cdn.hitfix.com/photos/5203303/Rick-Roll-Mash-Up.jpg','http://stream1.gifsoup.com/view2/1569461/rick-roll-o.gif','https://media4.giphy.com/media/lKm3FhZ6xMkFO/200_s.gif'];
var curbg = 0;

function changeBackground() {
    curbg++;
    if (curbg === (bgarray.length)) {
        curbg = 0;
    }
    var bgurl = bgarray[curbg];
    $(document.body).css('background-image','url("'+bgurl+'")');
}

setInterval(changeBackground,4000);
body {
  transition: background-image 1s;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Is this what you are looking to accomplish?

Comments