JavaScript - Colour Buttons
Aim
To use HTML Forms elements and JavaScript to create a web page that can change its background colour.
Tasks
(a) Create a new web page called "ColourButtons.htm", and type in the following code.
<html> <head> <script language="javascript"> function changeToRed() { document.body.bgColor = 'red'; } function changeToBlue() { document.body.bgColor = 'blue'; } </script> </head> <body> <h1>My Colourful Page</h1> <form name="myForm"> <input type="button" value="Red" onClick="changeToRed();"> <input type="button" value="Blue" onClick="changeToBlue();"> </form> </body> </html>
(b) Add one more button that changes the background to yellow.
(c) Make this page more efficient by deleting the functions inside the script section, and replacing them with:
function changeColor(c) { document.body.bgColor = c; }
Also alter the buttons to look like:
<input type="button" value="Red" onClick="changeColor('red');"> <input type="button" value="Blue" onClick="changeColor('blue');"> <input type="button" value="Yellow" onClick="changeColor('yellow');">
(d) Add three more buttons – one each for green, orange and purple.
(e) There are many other colour words that can be used to refer to specific colours. For example, "lime" is different from "green". Add three more buttons - one each for three colour words that seem to work.
page revision: 9, last edited: 06 Jul 2010 12:33






