View Full Version : Changing the table background after page loads using JavaScript

05-23-2005, 07:12 PM
I'm trying to make a page with two tables. The top table's background is randomly chosen from a list (I've only created the random function for that). Unfortunately, the TABLE tag has no NAME. So, is there any way that I can use this random function to manipulate the table background? If not, please give me some guidance.


05-23-2005, 09:01 PM
I think u r having trouble with changing the background of a table when your page is finished loading. Try this:

<script language="javascript">
function changeColor(){
document.getElementById('thetable').style.backgroundColor = "darkblue";
<body onload="changeColor();">
<table id="thetable">

05-24-2005, 07:33 AM
Thanks, that helps quite a bit. I modified it a little bit so that it would be random... but the line that makes all the difference doesn't work.

<TITLE>Man's Thing</TITLE>


var background = new Array(maxElements);
var maxElements = 5;
var num=0;

for (i=0; i<=maxElements; i++)
background[i] = new Image();
background[i].src = "bg" + (i+1) + ".gif";

function changeBackground()
var randNumber = Math.round(Math.random()*maxElements);
num = randNumber;
document.getElementById('thetable').style.background.src = background[num].src;



<BODY onLoad="changeBackground();" TOPMARGIN=0 LEFTMARGIN=0>



The getElementById line isn't causing the background to change. This assumes that I have maxElements number of images. Any help would be welcome.


05-24-2005, 07:37 AM
I havent done javascript in forever, and even when i did i wasn't very good with it.

But i program in other languages and in all of them you have to declare variables before you use them...is that different in javascript?

05-24-2005, 07:42 AM
I have declared all the variables... as far as I know.

05-24-2005, 07:50 AM
You did declare them...

I was just asking (mind you, i'm a newbie to javascript) would it be a problem if you set your array equil to a variable that hasn't been declared yet?

maxElements was declared after your array, but your array was declared as maxElements in size.

I didn't know if the browser goes and finds maxElements or not when its not defined. :confused:

05-24-2005, 10:39 AM
for (i=0; i<maxElements; i++)
background[i] = new Image();
background[i].src = "bg" + (i+1) + ".gif";

function changeBackground()
var randNumber = Math.floor(Math.random()*maxElements);
document.getElementById('thetable').style.background = "url("+background[randNumber].src+")";

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum