Forum Moderators: open

Message Too Old, No Replies

JS of a random CSS div background

         

grfxgirl

9:09 pm on Feb 10, 2005 (gmt 0)

10+ Year Member



I located a nice javascript in the CSS section of these forums that replaces a background image in a div with a random image. The script it great, but it has a flicker of the base div background before the random image loads:

<script type="text/javascript">
var backgroundSrcs = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg")
function pickimage()
{
var bgimage=backgroundSrcs[(Math.round(Math.random()*(backgroundSrcs.length-1)))]
document.getElementById("random").style.backgroundImage = "url('" + bgimage + "')";
}
</script>

<body onload="pickimage()">

Is there a way to stop the flicker while maintaining a copy of the div's base background image?

Thanks!

Bernard Marx

10:01 pm on Feb 10, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The script doesn't execute until the page loads. You need to do it sooner.

A couple of choices

1. call pickimage() in a small script block immediately after the img element appears in the HTML.

2. Use a document.write() statement to write the image HTML into the page.

BTW, your random code needs changing. Presently, the 7th image will never appear.
Replace Math.round with Math.floor