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?


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.

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

function ChangeIt()
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg'; = "repeat";// Background images repeat

// Web Page Design


<script type="text/javascript">

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); = colors[rand];
}, 30000);
var rand = Math.ceil(Math.random() * colors.length - 1); = 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.