Wednesday, July 1

Random CSS Background

The Case:
We have a header background image on the top of the site. The customer wants it to rotate randomly between any number of images.

The Javascript:

var images=new Array();
images[0] = "header1.jpg";
images[1] = "header2.jpg";
images[2] = "header3.jpg";
images[3] = "header4.jpg";
images[4] = "header5.jpg";
var path = "http://example.com/images/";

function changeHeader(){
var rn=Math.floor(Math.random()*images.length);
document.getElementById('header').style.background = "url('"+path+images[rn]+"')";
}
And the HTML:
<script type="text/javascript">
window.onload=function(){
changeHeader();
setInterval("changeHeader()",5000);
}</script>
Don't forget to set a default image for those who don't use javascript.

No comments: