Forum Moderators: open

Message Too Old, No Replies

To write a code inside DIV layer

Random image from a folder to make it DIV background

         

coldrain

6:59 am on May 1, 2007 (gmt 0)

10+ Year Member



hi all,

i have my header, where i do the following code to call a random image from the site folder:

<script language="javascript" type="text/javascript">

p=65*Math.random();
d=parseInt(p);
document.write ("<table background='../pics/site/"+d+".jpg'></table>");

</script>

but now i want to replace a table with a DIV, to make the pageload faster.

so i have tried the following:

document.write ("<div style="background: url('../pics/site/"+d+".jpg')"></div>")

but this is not working.
can You please help me, how to write the correct code?
thx.

Dabrowski

1:59 pm on May 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Using the DOM correctly, you should be able to do this easily enough.

In your HTML write your DIV as normal, but give it an ID.

<div id='content'>Text Text Text</div>

Then have a little inline script which applies the background image:

<script type='text/javascript'>  

var div = document.getElementById( "content");
var num = parseInt( Math.random() *65);
var img = "../pics/site/"+ num +".jpg";

div.style.backgroundImage = "url('"+ img +"');";

</script>

Now you're not writing your HTML with JS, that's generally bad practise unless you need to generate the content up-front.

You can run that code inline, or onload. It'll work either way, and you can shorten it to one line if you like.

Just incase you're not sure how it works, the getElementById function looks up any element on the page by it's id. Id's must be unique, no 2 the same on the same page.

The image name is generated the same.

The call to div.style.something sets the CSS properties on the element. Note you can't get the CSS properties this way.

It's also very bad practise to use '..' in a URI. If the path is not below the current directory, begin your URI with '/' to show an absolute path.