Inputs, Forms and Keys

A text box's current contents are input.value, and it is always text, even for type="number". Convert it with Number() before any math. Listen for the input event to react to every keystroke, or change to react when the person has finished.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

Every keystroke in the box fires an input event, and show() reads the box's value, which arrives as text, converts it with Number() and writes the answer. Calling show() once at the end fills the page in before anyone types.

YOUR TURN · WEB PAGE
Your turn → Turn it into a tip calculator: a box for the bill and a box for the tip percentage, showing the tip and the total, both updating as you type. Show money with two decimal places using toFixed(2).
loading editor…

Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.

Forms fire a submit event when someone presses Enter or a submit button. The browser's own response is to send the form somewhere and reload the page, which would wipe out your app. event.preventDefault() cancels that, so your code can handle it instead.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

preventDefault stopped the page from reloading, so the handler could check the address itself and answer on the page. aria-live makes screen readers announce the message whenever it changes.

Keys fire keydown. event.key is the character or the key's name, such as "Escape" or "Enter"; event.code names the physical key, such as "Space". Shortcuts listen on the whole document, and they should ignore keys typed into a box, or typing a space in a name would also pause your timer: if (event.target.matches("input, textarea")) return;

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

One listener on the document hears every key press. It returns straight away when the key was typed into the box, and otherwise checks which key it was. preventDefault on Space stops the page from scrolling.

◈ Graded Build

Whenever either box changes, show the total number of seconds in #total, written as N seconds. An empty box counts as 0, and seconds above 59 count as 59.

Checked by using your page: clicking, typing and waiting, then reading what changed. 3 visible and 1 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: One Listener, Many Buttons →
← Back