GarrettSadFace
GarrettSadFace

Reputation: 225

Random background when you refresh the page?

I have 14 images and I want the page to randomly select one of these when the page is loaded/refreshed.

Before I decided I wanted to use these images, I had a background with the following CSS code and it worked perfectly, and I want to use it for these new images as well:

 #bg {position:fixed; top: 0px; width:100%; height:100%; background: url('http://i.imgur.com/B8ubW70.jpg') center center no-repeat; background-size: cover; }

<div id="bg"></div>

Upvotes: 0

Views: 170

Answers (2)

bnson
bnson

Reputation: 222

My solution use JavaScript.

The first you created bgimg folder with images:

> index.html 
> bgimg (folder)
> -- 1.jpg
> -- 2.jpg
> -- 3.jpg
> -- ......

And use JavaScript below:

<html>
<head>
<script type="text/javascript">
var totalCount = 8;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimg/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
</script>
</head>
<body>
// Page Design
</body>
<script type="text/javascript">
ChangeIt();
</script>
</html>

Upvotes: 1

Tree Nguyen
Tree Nguyen

Reputation: 1199

You can use Math.random() to get the random picture index.

In your case, if you are having 14 pics, use this:

var picno = (Math.random() * 100) % 14 

This will return you a number between 0 and 13. After that, you can use element.style.backgroundImage() to change it on the onload event

window.onload = init

function init() {
    element.style.backgroundImage = url(pic_path_array[picno]);
}

Upvotes: 2

Related Questions