Leet School

{module 5}

A price calculator that responds

Your first JavaScript20 min read

What you will be able to do

  • Add a script to a page with a script element and defer.
  • Build a page that changes its own text while a visitor types.
  • Read the error in the Console when the script cannot find an element.

Why it matters

Steppe Wool is a small knitwear business in Ulaanbaatar, Mongolia. Oyunaa knits scarves from yak wool and sells them for $18 each. Most orders start as a message: "How much for three?" or "What do twelve cost?" Oyunaa answers each one herself, often late at night. One evening she wrote "$206" for twelve scarves when the right answer was $216, and she lost $10 on the order.

Every page you have built so far says the same thing to every visitor. A page with a small program on it can answer "how much for three?" by itself, the moment the visitor types the number.

The idea

The whole loop first

HTML says what is on a page. CSS says how it looks. The third language of the web, which you met in module 1, is JavaScript. It tells the browser what to do, step by step. A file of JavaScript is called a script, and its name ends in .js.

Here is the script you will build. Look at its shape, not its details:

From calculator.js
const quantityField = document.querySelector("#quantity");
const total = document.querySelector("#total");

function showTotal() {
  total.textContent = "Total: $" + quantityField.value * 18;
}

quantityField.addEventListener("input", showTotal);

When a visitor types 3 in the field, the line under it changes by itself to this:

Output
Total: $54

It does three things, as almost every script in this module does:

  1. Find the elements it needs: the field and the paragraph.
  2. Wait for something to happen: typing in the field.
  3. Change the page: the text of the paragraph.

The rest of this section takes the lines one at a time.

Adding a script to a page

You link a stylesheet with a link element in the head. You add a script with a script element, also in the head:

From index.html
<script src="calculator.js" defer></script>

src is the name of the script file, in the same folder as the page. defer tells the browser to run the script only after it has read the whole page. Without defer, the script runs while the browser is still in the head, before the elements in the body exist.

Finding an element

In module 2 you gave a field an id, so that its label could point to it. A script uses the same id to find the field:

From calculator.js
const quantityField = document.querySelector("#quantity");

Read it from the right. document is the page. querySelector looks through the page for an element, and "#quantity" says which one: the # means "the element whose id is".

The left side, const quantityField =, gives what was found a name, so the script can say quantityField from here on. Lesson 2 explains names like this.

Changing the text of the page

A property is a named piece of information that belongs to something. Every element has a property called textContent: the text inside it. When the script puts new text into it, the page changes at once. That is the line inside showTotal.

quantityField.value is what the visitor has typed in the field. * 18 multiplies it by 18, the price of a scarf. The + joins the words "Total: $" to the result. Text inside quotes is shown exactly as it is written.

Waiting for typing

Something that happens on a page is called an event: a click, a key pressed, a field changed. The event that happens every time the value of a field changes is called input. The last line of the script reads: on quantityField, when an input event happens, run showTotal.

showTotal is a function: a set of steps with a name, written between curly brackets. Writing a function does not run it. The script hands its name to the browser, and the browser runs it after each change to the field. A function used like this is called a listener. Lesson 3 is about functions.

The Console

In module 1 you met the Console, the part of the developer tools where errors appear. A script can write its own lines there with console.log. Visitors never see them. They are for you, to check that the script ran.

Worked example

Make a folder for this lesson and open it in Visual Studio Code with File, Open Folder. Create three files in it with the New File button in the Explorer, as in module 1: index.html, styles.css and calculator.js. Type each one as shown, and save it with Ctrl+S, or Cmd+S on a Mac.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Scarf calculator, Steppe Wool</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="calculator.js" defer></script>
  </head>
  <body>
    <main>
      <h1>Steppe Wool scarves</h1>
      <p>One scarf costs $18.</p>
      <label for="quantity">How many scarves?</label>
      <input type="number" id="quantity" value="1" />
      <p id="total">Total: $18</p>
    </main>
  </body>
</html>
styles.css
body {
  max-width: 40rem;
  margin: 0 auto;
  padding: 1rem;
  font-family: Arial, sans-serif;
  line-height: 1.5;
}

#total {
  font-size: 1.5rem;
  font-weight: bold;
}
calculator.js
const quantityField = document.querySelector("#quantity");
const total = document.querySelector("#total");

function showTotal() {
  total.textContent = "Total: $" + quantityField.value * 18;
}

quantityField.addEventListener("input", showTotal);
console.log("The calculator is ready.");

Open index.html in your browser by double-clicking it. The page shows this:

Output
Steppe Wool scarves

One scarf costs $18.

How many scarves?

Total: $18

Now open the Console. In Chrome and Edge press Ctrl+Shift+J, or Cmd+Option+J on a Mac. In Firefox press Ctrl+Shift+K, or Cmd+Option+K on a Mac. It shows the line the script wrote:

Output
The calculator is ready.

Click in the field, delete the 1 and type 3. The last line changes while you type:

Output
Total: $54

Change it to 12, Oyunaa's difficult order:

Output
Total: $216

Read calculator.js from the top.

Lines 1 and 2 find the field and the paragraph. Lines 4 to 6 are the function, which works out the total and puts it into the paragraph. Line 8 asks the browser to run it after each change to the field. Line 9 writes in the Console, so you know the script reached the end.

The HTML file still says "Total: $18". The script changed the page in the browser's memory, not the file. Reload the page and it starts again from the file.

Common mistakes

Leaving out defer

Remove defer from the script element, save, and reload:

From no-defer.html
<script src="calculator.js"></script>

Typing now changes nothing, and the Console shows an error in red:

Output
Total: $18
page error: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

The first line is the total on the page. The second comes from the Console: the tool that checks these lessons writes page error: before an error. In your browser you see the rest of the line, with calculator.js:8 beside it, the file and the line. These words are Chrome's. Firefox uses other words, and they also name null.

null means "nothing". Without defer, line 1 ran while the browser was still reading the head. The field did not exist yet, so querySelector found nothing and quantityField was null. Line 8 then asked nothing for addEventListener. Put defer back.

You get the same message when the id in the script and the id in the HTML are spelled differently. When you see "of null", check defer first, then check the selector letter by letter.

Brackets after the name of the function

Here the last line has two extra characters:

brackets.js
const quantityField = document.querySelector("#quantity");
const total = document.querySelector("#total");

function showTotal() {
  total.textContent = "Total: $" + quantityField.value * 18;
}

quantityField.addEventListener("input", showTotal());

Type 3 in the field. The page shows:

Output
Total: $18

There is no error. showTotal() with brackets means "run it now". It ran once, while the page loaded, and the browser was given nothing to run later. Without brackets, showTotal hands the function itself to the browser. Remove the brackets.

Think it through

Ji-ho sells handmade candles for $7 each. He wants a page where a visitor types a number of candles and sees "Candles: $21" for three.

Understand. In: a number typed in a field. Out: one line of text that changes while the visitor types. The price is $7.

Break down. A field and a paragraph in the HTML. A script that finds both. A function that writes the line. A listener that runs the function.

Plan. Copy the shape of the scarf calculator. Give the field id="candles" and the paragraph id="candle-total". Change the 18 to 7 and the words to "Candles: $".

Build. He writes the HTML and the script tag, then only line 1 with a console.log("found") under it, and reloads. The Console shows "found" and no red line, so the script runs. Then he adds the rest.

Test. 3 candles shows "Candles: $21", which is 3 times 7. The odd case is an empty field, which shows "Candles: $0". He notes it as a question for lesson 2.

Reflect. Checking the Console after each small step meant that an error could only come from the last line he added.

At work

A README is a file that explains a project to the next person who opens it. On GitHub it is named README.md and is shown under the list of files. You wrote one for your profile in orientation.

Many people read only the first screen of a README. It should answer three questions: what is this, who is it for, and where can I see it. Oyunaa's developer starts the README for the calculator like this:

Steppe Wool scarf calculator

A one-page price calculator for Steppe Wool, Ulaanbaatar. A customer types how many scarves they want and sees the total at once, at $18 a scarf.

Live page: https://example-user.github.io/steppe-wool-calculator/

It is one HTML file, one stylesheet and one script. Nothing needs to be installed.

Each line answers one of the three questions. The history of the project can wait for a later screen.

Your tasks

Task 1: Build the calculator

Create the three files from the worked example and open the page with the Console open.

You are done when typing 3 shows "Total: $54", and the Console shows "The calculator is ready." and no red line.

Task 2: Break it, then read it

Remove defer, reload and read the red message in the Console. Click the file name beside it to see the line. Put defer back. Then change "#quantity" to "#quantty", reload, and compare the message with the first one.

You are done when you have written down both messages and the line each one names, and the page works again.

Task 3: A second price

Oyunaa also sells hats at $12. Add a second field, "How many hats?", and a second paragraph that shows the total for hats while the visitor types. Keep the scarf total working.

You are done when 2 scarves and 3 hats show "Total: $36" and "Hats: $36", each updating while you type in its own field.

Recap

  • <script src="calculator.js" defer></script> in the head runs the script after the browser has read the whole page.
  • document.querySelector("#quantity") finds the element with that id, or gives null when there is none.
  • addEventListener("input", showTotal) runs the function each time the field changes. Pass the name with no brackets.
  • Setting textContent changes the text of an element on the page, not in the file.
  • console.log writes to the Console. Errors appear there too, so keep it open.

Go deeper