Web development

Magic Button

Write your first JavaScript: a button that gives a random compliment and changes the colour of the page.

Day 4 45 to 60 minutes 6 steps Key Stage 3
Start step 1
magic-button/index.html

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. const never changes; let can.

Step by step

  1. 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 runs script.js, which is empty for now.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Magic Compliment Machine</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Magic Compliment Machine</h1>    <button id="magic">Press me!</button>    <p id="message">Press the button for a compliment.</p>    <script src="script.js"></script>  </body></html>
    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  padding: 30px;}
    script.jsJavaScript
     
    magic-button/index.html
    A button that does nothing yet.
  2. Step 2: Make it do something

    Click the script.js tab. document.getElementById("magic") finds the element whose id is magic, and const keeps it in a variable called button. addEventListener("click", ...) runs the function whenever the button is clicked, and the function changes the paragraph's text.

    script.jsJavaScript
    const button = document.getElementById("magic");const message = document.getElementById("message"); button.addEventListener("click", function () {  message.textContent = "You are awesome!";});
    magic-button/index.html
    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.
  3. 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 with Math.floor picks a random position: 0, 1, 2, 3, 4 or 5.

    New: lines 4 to 12, 14 and 15.

    script.jsJavaScript
    const button = document.getElementById("magic");const message = document.getElementById("message"); const compliments = [  "You are awesome!",  "Your code is amazing!",  "You make the world brighter.",  "You are a great friend.",  "You could build anything!",  "Your ideas are brilliant."]; button.addEventListener("click", function () {  const i = Math.floor(Math.random() * compliments.length);  message.textContent = compliments[i];});
    magic-button/index.html
    Every press picks one of six compliments.
  4. 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.

    script.jsJavaScript
    const button = document.getElementById("magic");const message = document.getElementById("message"); const compliments = [  "You are awesome!",  "Your code is amazing!",  "You make the world brighter.",  "You are a great friend.",  "You could build anything!",  "Your ideas are brilliant."];const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"]; button.addEventListener("click", function () {  const i = Math.floor(Math.random() * compliments.length);  message.textContent = compliments[i];  const c = Math.floor(Math.random() * colours.length);  document.body.style.background = colours[c];});
    magic-button/index.html
    Each press changes the background colour too.
  5. Step 5: Count the compliments

    Add a paragraph to count with. let makes a variable that can change, unlike const, and every click adds one to it.

    New: line 12.

    index.htmlHTML
    <!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Magic Compliment Machine</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Magic Compliment Machine</h1>    <button id="magic">Press me!</button>    <p id="message">Press the button for a compliment.</p>    <p id="counter">Compliments given: 0</p>    <script src="script.js"></script>  </body></html>

    New: lines 3, 14, 21 and 22.

    script.jsJavaScript
    const button = document.getElementById("magic");const message = document.getElementById("message");const counter = document.getElementById("counter"); const compliments = [  "You are awesome!",  "Your code is amazing!",  "You make the world brighter.",  "You are a great friend.",  "You could build anything!",  "Your ideas are brilliant."];const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"];let clicks = 0; button.addEventListener("click", function () {  const i = Math.floor(Math.random() * compliments.length);  message.textContent = compliments[i];  const c = Math.floor(Math.random() * colours.length);  document.body.style.background = colours[c];  clicks = clicks + 1;  counter.textContent = "Compliments given: " + clicks;});
    magic-button/index.html
    A running total under the compliment.
  6. Step 6: A magic looking button

    Finally, style it. #magic in CSS styles the element with the id magic. border-radius: 50px makes the button pill shaped, and cursor: pointer shows a hand when you point at it.

    New: lines 6 to 24.

    style.cssCSS
    body {  font-family: Arial, sans-serif;  text-align: center;  padding: 30px;} #magic {  font-size: 24px;  padding: 20px 40px;  border: none;  border-radius: 50px;  background: #8e44ad;  color: white;  cursor: pointer;} #magic:hover {  background: #a95fd0;} #message {  font-size: 28px;  font-weight: bold;}
    magic-button/index.html
    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.

  1. 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.

  2. 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 while loop as long as the new number is the same as the last one.

  3. 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").value is what was typed. Join it on with +.

The finished code

Show the whole page
index.htmlHTML
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>Magic Compliment Machine</title>    <link rel="stylesheet" href="style.css">  </head>  <body>    <h1>Magic Compliment Machine</h1>    <button id="magic">Press me!</button>    <p id="message">Press the button for a compliment.</p>    <p id="counter">Compliments given: 0</p>    <script src="script.js"></script>  </body></html>
style.cssCSS
body {  font-family: Arial, sans-serif;  text-align: center;  padding: 30px;} #magic {  font-size: 24px;  padding: 20px 40px;  border: none;  border-radius: 50px;  background: #8e44ad;  color: white;  cursor: pointer;} #magic:hover {  background: #a95fd0;} #message {  font-size: 28px;  font-weight: bold;}
script.jsJavaScript
const button = document.getElementById("magic");const message = document.getElementById("message");const counter = document.getElementById("counter"); const compliments = [  "You are awesome!",  "Your code is amazing!",  "You make the world brighter.",  "You are a great friend.",  "You could build anything!",  "Your ideas are brilliant."];const colours = ["#ffd6e0", "#d6f5ff", "#e2ffd6", "#fff3c4", "#e9dcff"];let clicks = 0; button.addEventListener("click", function () {  const i = Math.floor(Math.random() * compliments.length);  message.textContent = compliments[i];  const c = Math.floor(Math.random() * colours.length);  document.body.style.background = colours[c];  clicks = clicks + 1;  counter.textContent = "Compliments given: " + clicks;});
Notes for the teacher

Timing

  1. 10 minutes: step 1. Look at the id attributes, and point out the <script> at the end of the body.
  2. 25 minutes: steps 2 to 4. Step 2 is the big idea: an event listener waits for a click, then runs a function.
  3. 15 minutes: steps 5 and 6, and the tests.

Mistakes to look out for

  1. getElementByID or getelementbyid: JavaScript is case sensitive, so nothing works. Open the browser's console (F12) to see the error.
  2. The id in the HTML and the one in the JavaScript do not match: getElementById gives null, and the next line fails.
  3. A missing bracket or brace at the end: }); closes the function, then the call to addEventListener.
  4. 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.