Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.
In this exercise, you will modify a page called ColorMania.html, which will contain a form
with four buttons. Each button will show the name of a color (e.g., red) and, when clicked, call a function that changes the background color. The buttons you will create will be of type button
. For example,
<input type="button" value="red" onclick="functionCall();">
changeBg()
that changes the background
color and then pops up an alert telling the user, by name, what
the new background color is.changeBg()
function and pass it a color value.The resulting page should look like this:
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Colormania</title> <script> //PROMPT USER FOR NAME /* Write a function called changeBg() that changes the background color and then pops up an alert telling the user, by name, what the new background color is. */ </script> </head> <body> <form> <!--ADD BUTTONS HERE--> </form> </body> </html>
Add another button called "custom" that, when clicked, prompts the user for a color, then changes the background color to the user-entered color and alerts the user to the change.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Colormania</title> <script> var userName = prompt("Your name?", ""); function changeBg(color){ document.body.style.backgroundColor = color; alert(userName + ", the background color is " + color + "."); } </script> </head> <body> <form> <input type="button" value="red" onclick="changeBg('red');"> <input type="button" value="green" onclick="changeBg('green');"> <input type="button" value="blue" onclick="changeBg('blue');"> <input type="button" value="orange" onclick="changeBg('orange');"> </form> </body> </html>
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Colormania</title> <script> var userName = prompt("Your name?", ""); function changeBg(color){ document.body.style.backgroundColor = color; alert(userName + ", the background color is " + color + "."); } function customBg(){ var userColor = prompt("Choose a color:", ""); changeBg(userColor); } </script> </head> <body> <form> <input type="button" value="red" onclick="changeBg('red');"> <input type="button" value="green" onclick="changeBg('green');"> <input type="button" value="blue" onclick="changeBg('blue');"> <input type="button" value="orange" onclick="changeBg('orange');"> <input type="button" value="custom" onclick="customBg();"> </form> </body> </html>
This tutorial is based on Webucator's Introduction to JavaScript Training Course. We also offer many other JavaScript Training courses. Sign up today to get help from a live instructor.