HTML changing background color with javascript

How do you change the background colour of your webpage via javascript?

The more experienced people will notice that this tutorial is doing slightly more than is required to effect a change in background color, but it shouldn’t throw off the novice in the slightest. Things like comments or variable declarations are not needed here, but they also do no harm either for the purpose of this tutorial.

A less forgiving environment might require you to close your “option” tags and to put semi-colons at the end of your javascript statements.

We will put the javascript into the head of the webpage

<html>
<head>
<script type=”text/javascript”>
function displayResult()
{

var color1  = somename.value
document.body.bgColor=color1
}
</script>
</head>

The variable color1 is used to store the value of an item with the id somename. It is actually the id of the dropdown menu which we will use to select the background color.

<body>

<h1>Hello World!</h1>
<br />

<!– This is a comment –>
<!–
<button type=”button” onclick=”displayResult()”>Set background color</button>
–>

<select id=”somename” onchange=”displayResult()”>
<option value=”#FFF000″>yellow
<option value=”blue”>blue
<option value=”red”>red
<option value=”lavender”>weird
</select>

</body>
</html>

This should result in something similiar to this

Proceed now, to select a color and you should see the color change.

 

The entire code that you should have now is this:

<html>
<head>
<script type=”text/javascript”>
function displayResult()
{

var color1  = somename.value
document.body.bgColor=color1
}
</script>
</head><body>

<h1>Hello World!</h1>
<br />

<!– This is a comment –>
<!–
<button type=”button” onclick=”displayResult()”>Set background color</button>
–>

<select id=”somename” onchange=”displayResult()”>
<option value=”#FFF000″>yellow
<option value=”blue”>blue
<option value=”red”>red
<option value=”lavender”>weird
</select>

</body>
</html>

 

Change the code to the following:

<html>
<head>
<script type=”text/javascript”>
function displayResult()
{

var color1  = somename.value
document.body.bgColor=color1
}
</script>
</head><body>

<h1>Hello World!</h1>
<br />

<button type=”button” onclick=”displayResult()”>Set background color</button>

<select id=”somename”>
<option value=”#FFF000″>yellow
<option value=”blue”>blue
<option value=”red”>red
<option value=”lavender”>weird
</select>

</body>
</html>

Now you are required you to click the button to effect the change.

A good resource to learn and try out some HTML and Javascript (and lots of other cool things), is w3schools website (http://www.w3schools.com/). They provide very good tutoritals and examples. They also allow you to play with a “Try it yourself editor” where you can make changes to the html and see the effects right away.

Comments are closed.