BoeNoe BoeNoe - 2 months ago 8
HTML Question

How to make a random image on background

I want on my website where every 5 minutes the background changes to a new image. I want this done with jQuery if possible.

I want it to loop through 3 images. How to do this?

Here is my current code:

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='jquery-3.1.1.min.js'></script>
<script type='text/javascript' src='jquery-ui/jquery-ui.js'></script>

<script type='text/javascript'>
$(document).ready(function(){
setInvetval(function(){
$('body').css('background-image', 'image-path');
}, 300000);
});
</script>
</head>

<body>

</body>
</html>

Answer

It's a bit unclear but i guess you need something like the code below, you can run it works:

$(document).ready(function(){
    // initializing the index
    var actual = 0;

    // interval implementation
    setInterval(function(){     
 
        // setting the image
        $('body').css('background', "url('" + my_image_array[actual] + "')");
        
        // contrilling the index
        if (actual == my_image_array.length) {
          actual = 0;
        } else {
          actual = actual + 1;
        }
        
        // debugging the index
        //console.log(actual);
    }, 800); // 300000, have setted short time for tests
});

// Instantiating array
var my_image_array = new Array();

// Some images in an array structure
my_image_array[0] = 'https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg';
my_image_array[1] = 'http://static8.depositphotos.com/1003153/893/v/950/depositphotos_8938809-Example-rubber-stamp.jpg';
my_image_array[2] = 'http://thumb7.shutterstock.com/display_pic_with_logo/436114/268701041/stock-vector-example-blue-square-grunge-textured-isolated-stamp-268701041.jpg';
my_image_array[3] = 'http://garsonadvogados.com.br/wp-content/uploads/2015/08/example3.jpg';
my_image_array[4] = 'http://st.depositphotos.com/1023799/2906/v/950/depositphotos_29066941-Grunge-example-rubber-stamp-vector.jpg';
/* basic style to the body */
body{width:100%; height:100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

Comments