...

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



abannet
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.

Cheers.
-Alan

jshl_wiz
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:



<head>
<script language="javascript">
<!--
function changeColor(){
document.getElementById('thetable').style.backgroundColor = "darkblue";
}
//-->
</script>
<body onload="changeColor();">
<table id="thetable">
<tr><td>something</td></tr>
</table>

abannet
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.



<HTML>
<HEAD>
<TITLE>Man's Thing</TITLE>

<SCRIPT LANGUAGE="JavaScript">

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;
}

</SCRIPT>

</HEAD>

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

<TABLE ID="thetable" WIDTH=100% HEIGHT=200 BORDER=1 CELLPADDING=0 CELLSPACING=0>
<TR><TD>something</TD></TR>
</TABLE>

</BODY>
</HTML>


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

Cheers.
-Alan

CowboyInMe
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?

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

CowboyInMe
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:

glenngv
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