Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

table cell with random background

Status
Not open for further replies.

davikokar

Technical User
Joined
May 13, 2004
Messages
523
Location
IT
hi,

I am trying to have a table cell with a random image as background. The random image would be chose among four possible images.

I am using this code but it doesn't work:

Code:
<script language="javascript" type="text/javascript">
var img_rnd = new Array ();

img_rnd[0] = "img/background_index_01.jpg";
img_rnd[0] = "img/background_index_02.jpg";
img_rnd[0] = "img/background_index_03.jpg";
img_rnd[0] = "img/background_index_04.jpg";

var i = Math.floor(Math.random() * 4);

document.getElementById('back').bg=img_rnd[i];
//-->
</script>

and then of course the html:

Code:
<td class="index_bottom" id="back" name="back">

do you see any mistake?
thanks
 
ehm.... yes... a part from this error, the debugger still tell me that

document.getElementById('back').bg=img_rnd;

is null or not an object...

any idea?
thanks
 
yes, normallyw ith css I would use the background-image property to set a background of a cell. But when it comes to javascript... I don't know how to refer to it:

bg ?
background ?
background-image ?

none of these worked.

By the way... do you know a knowledge base for javascript. Something similar to the one that Microsoft produced for VB.NET... where all objects are listed with all properties, and so on...?

thanks for the help
 
To refere to it in javascript, use this.
[tt]document.getElementById("back").style.backgroundImage[/tt]
 
thanks for the answers...
I am trying with this code, updated with your suggestion. But I still get an error message "object required" on the line with the document.getElementByID....

Code:
<script language="javascript" type="text/javascript">
var img_rnd = new Array ();

img_rnd[0] = "img/background_index_01.jpg";
img_rnd[1] = "img/background_index_02.jpg";
img_rnd[2] = "img/background_index_03.jpg";
img_rnd[3] = "img/background_index_04.jpg";

var i = Math.floor(Math.random() * 4);

document.getElementById("back").style.backgroundImage=img_rnd[i];

//-->
</script>
 
Like this.
[tt] document.getElementById("back").style.backgroundImage=[red]"url([/red]img_rnd[red])"[/red];
[/tt]
 
mah... this still gives me the same error.... I am sure the pictures exist in the right place. what else can be?
 
My mistake. Your path is a variable. Here is the amendment.
[tt]
document.getElementById("back").style.backgroundImage=[red]"url("+[/red]img_rnd[red]+")"[/red];
[/tt]


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top