Web development
Magic Button
Write your first JavaScript: a button that gives a random compliment and changes the colour of the page.
HTML says what is on a page and CSS how it looks. JavaScript makes it do things. Today you will build a Magic Compliment Machine: press the button and it says something nice about you, in a new colour every time.
You will learn
- Find an element on the page with
getElementById - Run code when a button is clicked
- Pick at random from an array
- Change words and colours with code
You will need
- A computer with a web browser
- The Web Studio, or Notepad
- Days 1 and 2, for HTML and CSS
Words to know
- JavaScript
- The language that makes web pages do things.
- event
- Something that happens, such as a click, that code can respond to.
- array
- A list of values in square brackets. The first one is number 0.
- variable
- A named value.
constnever changes;letcan.
Step by step
Step 1: A button on the page
In the Web Studio, choose Day 4: Magic Button. The page has a button and a paragraph, each with an
id, a unique name the code can find it by. The<script>line at the end of the body runsscript.js, which is empty for now.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Magic Compliment Machine</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Magic Compliment Machine</h1>10 <button id="magic">Press me!</button>11 <p id="message">Press the button for a compliment.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 padding: 30px;5}1A button that does nothing yet. Step 2: Make it do something
Click the script.js tab.
document.getElementById("magic")finds the element whose id ismagic, andconstkeeps it in a variable calledbutton.addEventListener("click", ...)runs the function whenever the button is clicked, and the function changes the paragraph's text.1const button = document.getElementById("magic");2const message = document.getElementById("message");3 4button.addEventListener("click", function () {5 message.textContent = "You are awesome!";6});Press the button in the page above: a compliment appears. Watch out Capital letters matter in JavaScript:getElementById, with a capital E, B and I.Step 3: A random compliment
An array is JavaScript's list: values in square brackets, separated by commas.
Math.random()gives a random number from 0 up to 1, so multiplying by the length of the array and rounding down withMath.floorpicks a random position: 0, 1, 2, 3, 4 or 5.New: lines 4 to 12, 14 and 15.
1const button = document.getElementById("magic");2const message = document.getElementById("message");3 4const compliments = [5 "You are awesome!",6 "Your code is amazing!",7 "You make the world brighter.",8 "You are a great friend.",9 "You could build anything!",10 "Your ideas are brilliant."11];12 13button.addEventListener("click", function () {14 const i = Math.floor(Math.random() * compliments.length);15 message.textContent = compliments[i];16});Every press picks one of six compliments. Step 4: A splash of colour
Pick a random colour from a second array, and set the page's background to it with
document.body.style.background.New: lines 12, 17 and 18.
1const button = document.getElementById("magic");2const message = document.getElementById("message");3 4const compliments = [5 "You are awesome!",6 "Your code is amazing!",7 "You make the world brighter.",8 "You are a great friend.",9 "You could build anything!",10 "Your ideas are brilliant."11];12const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"];13 14button.addEventListener("click", function () {15 const i = Math.floor(Math.random() * compliments.length);16 message.textContent = compliments[i];17 const c = Math.floor(Math.random() * colours.length);18 document.body.style.background = colours[c];19});Each press changes the background colour too. Step 5: Count the compliments
Add a paragraph to count with.
letmakes a variable that can change, unlikeconst, and every click adds one to it.New: line 12.
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Magic Compliment Machine</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Magic Compliment Machine</h1>10 <button id="magic">Press me!</button>11 <p id="message">Press the button for a compliment.</p>12 <p id="counter">Compliments given: 0</p>13 <script src="script.js"></script>14 </body>15</html>New: lines 3, 14, 21 and 22.
1const button = document.getElementById("magic");2const message = document.getElementById("message");3const counter = document.getElementById("counter");4 5const compliments = [6 "You are awesome!",7 "Your code is amazing!",8 "You make the world brighter.",9 "You are a great friend.",10 "You could build anything!",11 "Your ideas are brilliant."12];13const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"];14let clicks = 0;15 16button.addEventListener("click", function () {17 const i = Math.floor(Math.random() * compliments.length);18 message.textContent = compliments[i];19 const c = Math.floor(Math.random() * colours.length);20 document.body.style.background = colours[c];21 clicks = clicks + 1;22 counter.textContent = "Compliments given: " + clicks;23});A running total under the compliment. Step 6: A magic looking button
Finally, style it.
#magicin CSS styles the element with the idmagic.border-radius: 50pxmakes the button pill shaped, andcursor: pointershows a hand when you point at it.New: lines 6 to 24.
1body {2 font-family: Arial, sans-serif;3 text-align: center;4 padding: 30px;5}6 7#magic {8 font-size: 24px;9 padding: 20px 40px;10 border: none;11 border-radius: 50px;12 background: #8e44ad;13 color: white;14 cursor: pointer;15}16 17#magic:hover {18 background: #a95fd0;19}20 21#message {22 font-size: 28px;23 font-weight: bold;24}The finished Magic Compliment Machine. Press it!
Test it
Tick each one when it works. If one does not, look back at the step it comes from.
Stretch challenges
Finished early? Try these. Each one has a hint if you get stuck.
More compliments
Add five more compliments of your own to the array.
Show a hint
Each one is in quotes, with a comma after it, except the last.
Never the same twice
Make sure the same compliment never comes up twice in a row.
Show a hint
Keep the last number in a variable. Pick again in a
whileloop as long as the new number is the same as the last one.Compliment for a name
Add a box to type a name into, and put the name in front of the compliment.
Show a hint
Add
<input id="name">to the page. In the click function,document.getElementById("name").valueis what was typed. Join it on with+.
The finished code
Show the whole page
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Magic Compliment Machine</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Magic Compliment Machine</h1>10 <button id="magic">Press me!</button>11 <p id="message">Press the button for a compliment.</p>12 <p id="counter">Compliments given: 0</p>13 <script src="script.js"></script>14 </body>15</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 padding: 30px;5}6 7#magic {8 font-size: 24px;9 padding: 20px 40px;10 border: none;11 border-radius: 50px;12 background: #8e44ad;13 color: white;14 cursor: pointer;15}16 17#magic:hover {18 background: #a95fd0;19}20 21#message {22 font-size: 28px;23 font-weight: bold;24}1const button = document.getElementById("magic");2const message = document.getElementById("message");3const counter = document.getElementById("counter");4 5const compliments = [6 "You are awesome!",7 "Your code is amazing!",8 "You make the world brighter.",9 "You are a great friend.",10 "You could build anything!",11 "Your ideas are brilliant."12];13const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"];14let clicks = 0;15 16button.addEventListener("click", function () {17 const i = Math.floor(Math.random() * compliments.length);18 message.textContent = compliments[i];19 const c = Math.floor(Math.random() * colours.length);20 document.body.style.background = colours[c];21 clicks = clicks + 1;22 counter.textContent = "Compliments given: " + clicks;23});Notes for the teacher
Timing
- 10 minutes: step 1. Look at the
idattributes, and point out the<script>at the end of the body. - 25 minutes: steps 2 to 4. Step 2 is the big idea: an event listener waits for a click, then runs a function.
- 15 minutes: steps 5 and 6, and the tests.
Mistakes to look out for
getElementByIDorgetelementbyid: JavaScript is case sensitive, so nothing works. Open the browser's console (F12) to see the error.- The
idin the HTML and the one in the JavaScript do not match:getElementByIdgivesnull, and the next line fails. - A missing bracket or brace at the end:
});closes the function, then the call toaddEventListener. - Curly quotes pasted from a document instead of straight quotes.
Going further
Compare the click event with tkinter's command= in the Python track: two languages, the same idea of event driven programming.