We help IT Professionals succeed at work.

How do I change the body background color with an input button?

shampouya
shampouya asked
on
Medium Priority
619 Views
Last Modified: 2012-03-12
I can't figure out why none of these three attempts are changing the background color of my webpage linked below. Does anyone know why?

<input type="button" onClick="document.body.style.background-color='lavender';" value="Change background color" />
<ul>
	<li><img src="lavenderSquare.jpg" onClick="return backgroundLavender()"></img></li>
	<li><a href="#" onClick="javascript:changeBGC('#000099')">Click Blue</a></li>
</ul>

Open in new window


http://wdiclass.com/poureb/homework4special/homework4special.html
Comment
Watch Question

Chris AshcraftSenior Analyst - Technology
CERTIFIED EXPERT

Commented:
It should be "backgroundColor" - not "background-color" for javascript.

So...

document.body.style.backgroundColor='lavender';
CERTIFIED EXPERT

Commented:
you can just use this document.bgColor if you want to change the page color see below

<input type="button" onClick="document.bgColor='lavender';" value="Change background color" />

Author

Commented:
I see, and how come this separate function doesn't work?

<script>
function backgroundLavender(){
	document.bgColor="lavender";
}
</script>

<ul>
<li><img src="lavenderSquare.jpg" onClick="backgroundLavender()"></img></li>
</ul>

Open in new window

CERTIFIED EXPERT

Commented:
It should work , it is working for me .

Author

Commented:
So when you click on the lavender square image, the body background turns lavender?
CERTIFIED EXPERT

Commented:
Yes , which browser are you using ?

Author

Commented:
Using firefox 8.0. I am able to change the background with the "Change Background Color" button, but not with with the small purple square image. Any idea why the purple square does nothing?
CERTIFIED EXPERT

Commented:
You can do it in diff ways
1)

<input type="button" onClick="document.bgColor='lavender';" value="Change background color" />

2)

function changeBackground() {
   document.body.style.background = 'lavender';
}


3)
Write a css func

<style>
body.lavbg
{
  background: lavender;
}
</style>
<input type="button" onClick="document.body.className='lavbg';" value="Change background color" />
CERTIFIED EXPERT
Commented:
Try this it should work
<style>
body.lavbg
{
  background: lavender;
}
</style>

<ul>
<li><img src="lavenderSquare.jpg" onClick="document.body.className='lavbg';"></img></li>
</ul>

Author

Commented:
Actually, this worked:

function changeBackground() {
   document.body.style.background = 'lavender';
}

Author

Commented:
You're right

Author

Commented:
thanks

Explore More ContentExplore courses, solutions, and other research materials related to this topic.