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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Change Background Colour

Status
Not open for further replies.

icu222much

Technical User
Mar 12, 2007
26
0
0
CA
I am wondering how I would change the background colour of a document. The following is my approach, but it does not seem to work:

Code:
function changeBgColour() {
  document.write("<body bgcolor=#00FF00>");
}

I found out that the proper way is:

Code:
function changeBgColour() {
  document.bgColor = '#00FF00;
}

I am wondering why my first approach did not work?
 
Is there a reason why my first approach did not work? From my understanding, document.write() will write any text to the page thus I can do <b>Hi</b> and it will display bold Hi.
 
icu222much you are correct that document.write will output whatever you pass it, but what you have is probably something like

INITIAL HTML
Code:
<html>
<head>
<script>
function changeBgColour() {
  document.write("<body bgcolor=#00FF00>");
} 
</script>
</head>
<body bgcolor="red">
hello world
<script>changeBgColour()</script>
</body>
</html>

What the above results in is that the
Code:
changeBgColour
function writes out the HTML in it at its place, so you would get :

Code:
<html>
<head>
</head>
<body bgcolor="red">
hello world
[b]<body bgcolor=#00FF00>[/b]
</body>
</html>

so what you want to do is update the value rather than add an extra row with a different value.

Does that clarify it for you?

Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005 & 2006
 
I actually did not call the function inside the body tag. Instead, I called the function within the body tag. I did:

Code:
<body onLoad="changeByColour()">
{/code]

Would this still have the same effect you speak of?
 
icu222much,
in the code you show above, you are printing a second body tag, in addition to the one you already have that contains the OnLoad event, when the HTML page is loaded, which is too late, as well as the invalid position of having more than one BODY tag.

I assume that your example is a contrived example, because if you only have a single colour value for the background, then I would just set it either on the page :

Code:
<body bgcolor="red">

or probably better via CSS - inline on the page or an external CSS style sheet.

If you have multiple colours and additional logic, I would use the format that feherke mentions above.

Greg Griffiths
Livelink Certified Developer & ECM Global Star Champion 2005 & 2006
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top