Alerts, Writing, and Changing Background Color - Exercise

Contact Us or call 1-877-932-8228
Alerts, Writing, and Changing Background Color - Exercise

Alerts, Writing, and Changing Background Color

Duration: 5 to 15 minutes.

In this exercise, you will practice using JavaScript to popup an alert, write text to the screen, and set the background color of the page.

  1. Open JavaScriptBasics/Exercises/alert-write-bgcolor.html for editing.
  2. In the head of the file, add a JavaScript alert which pops up the message "Welcome to my page!" when the page loads.
  3. Add click handlers to the two buttons to allow the user to change the background color of the page to red or to blue.
  4. In the script at the bottom of the page, use JavaScript to write the text "This text was generated by JavaScript" to the page.
  5. Test your solution in a browser.

Solution:

JavaScriptBasics/Solutions/alert-write-bgcolor.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Alert, Write, BGColor</title>
<script>
	window.alert("Welcome to my page!");
</script>
</head>
<body>
<form>
	<p>Click the button to turn the page:<p>
	<button onclick="document.body.style.backgroundColor = 'red'; return false">Red</button>
	<p>Click the button to turn the page:<p>
	<button onclick="document.body.style.backgroundColor='blue'; return false">Blue</button>
</form>
<hr>
<script>
	document.write('This text was generated by JavaScript');
</script>
</body>
</html>

Code Explanation

We use alert() to generate the popup the head and document.write() to write to the screen at the bottom of the page. We use onclick="document.body.style.backgroundColor='red' to add a click handler to the button; return false ensures that the page does not reload when the button is clicked.

Next