Sevencolors studies:
experiments with Javascript, CSS, PHP and web standards

Printer icon

Background image

Javascript random images

function preload()
var args = preload.arguments;
document.imgArray = new Array(args.length);
for(var i=0; i<args.length; i++)
document.imgArray[i] = new Image;
document.imgArray[i].src = args[i];
function randomImg(){
var q = new Array('image1','image2','image3');
var n = parseInt(Math.floor(Math.random()*3)); = 'url('+ q[n] +') fixed no-repeat center right #efefef';
window.onload = randomImg;

I call the function with a window.onload which causes the image to change everytime the page loads. In Netscape 7 it`s a bit trickier then in IE 6, sometimes it shows the same image three or four times in a row. The preload is necessary, otherwise sometimes the image doesn`t appear on the screen.

Updated on 2004/03:

That code was used in the first version, now I`ve changed it so that instead of attaching images to the background it displays text in a span. No need for a preload anymore. The change was brought over by the flow of the new design:

function randomQuotes()
var q = new Array('quote1','quote2','quote3');
var n = parseInt(Math.floor(Math.random()*3));
var rq = document.getElementById('quotes');
if(!rq) return;
rq.innerHTML = q[n];
window.onload = randomQuotes;

The tricky part is writing the quotes, which in Javascript are 'strings' (text to be rendered as such). If the phrase has to break up using a <br /> tag, it must be escaped like this:

\<br /\>

otherwise the parser doesn`t recognize it as a tag and renders it as part of the string.