Randomized background image code with javascript

2018 views javascript
9

I have the javascript code below to change the background randomly but it doesn't work after setting the first image. Where is the problem?

var images = [
    {src: "images/bg1_mod.jpg"},
    {src: "images/bg2_mod.jpg"},
    {src: "images/bg3_mod.png"},
    {src: "images/bg4_mod.png"},
    {src: "images/bg5_mod.jpg"},
    {src: "images/bg6_mod.jpg"},
    {src: "images/bg7_mod.png"},
    {src: "images/fftactics_mod.jpg"}
];

function setBackground(images){
    var n = Math.floor(Math.random() * images.length),
        textProperty = "textContent" in document ? "textContent" : "innerText";
    document.body.style.backgroundImage = "url(" + images[n].src + ")";
}
while(1>0){
    setBackground(images);
    sleep(3000);
}

answered question

what is sleep? Have you defined it anywhere? Also check the console for any errors. (I suspect that the sleep call is throwing an error, and therefore the function is only running once.)

Whatever sleep is you're far better off using a setInterval here instead of that while loop.

@Andy, just a question, would document.body.style.backgroundImage = ... reload the background of the element? I mean shouldn't there be something like reload() or anything that reloads the body with the new Image ?

1 Answer

6

Try to use setInterval()function:

var images = [
    {src: "images/bg1_mod.jpg"},
    {src: "images/bg2_mod.jpg"},
    {src: "images/bg3_mod.png"},
    {src: "images/bg4_mod.png"},
    {src: "images/bg5_mod.jpg"},
    {src: "images/bg6_mod.jpg"},
    {src: "images/bg7_mod.png"},
    {src: "images/fftactics_mod.jpg"}
];

function setBackground(images){
    var n = Math.floor(Math.random() * images.length),
    var textProperty = "textContent" in document ? "textContent" : "innerText";
    document.body.style.backgroundImage = "url(" + images[n].src + ")";
}

let interval = setInterval(setBackground, 3000);

(You've also missed var statement before 'textProperty', bt that's not the issue)

posted this

Have an answer?

JD

Please login first before posting an answer.