Javascript for random background image?

They have: 3 posts

Joined: Feb 2012

I have been looking for some Javascript to randomly change the background image on a Web page each time it is either loaded or refreshed. There are many potential solutions out there, but does anyone here have a clean script that I can use?

TIA

JamesSmith's picture

They have: 22 posts

Joined: Apr 2012

Hi Straysaver,

Try this code snippets, it might be work as you want or do some changes in the code as per your requirement.

<html>
<head>
<script type="text/javascript">
var totalCount = 11;

function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background images repeat
}
</script>
</head>
<body>

// Web Page Design

</body>

<script type="text/javascript">
ChangeIt();
</script>
</html>

or you may also try it....

var colors = [
    "red", "blue", "green", "yellow", "red"
    ];
var t = setInterval(function() {
    var rand = Math.ceil(Math.random() * colors.length - 1);
    document.body.style.backgroundColor = colors[rand];
}, 30000);
var rand = Math.ceil(Math.random() * colors.length - 1);
document.body.style.backgroundColor = colors[rand];

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.