Toasts and Overlays

Every action deserves an answer the person can see. A toast is a short message that appears and fades by itself: add a show class, then use setTimeout to remove it a couple of seconds later. Keep the timer's id, and clear it before starting a new one, so a second message restarts the countdown instead of vanishing early.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

showToast writes the message, adds show so the CSS fades it in, and schedules its removal. Clearing the old timer first means clicking twice keeps the message up for the full time. role="status" makes screen readers announce it.

YOUR TURN · WEB PAGE
Your turn → Add a Delete button that shows a different message. Then give showToast a second parameter for how long the message stays, with a default of 2400.
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.

An overlay covers the page to demand attention, such as an alarm going off. Hide it with display: none in CSS and show it by adding a class. Mark it role="dialog" and aria-modal="true" with a heading, close it with a button and with the Escape key, and move focus onto its main button so keyboard users land inside it.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

The overlay is always in the page, just hidden. Adding show switches it to display: grid, and focus() moves the keyboard onto its button. Escape closes it only while it is showing.

◈ Graded Build

Write showToast(message). It puts the message in #toast, adds the class show, and removes the class 2.4 seconds later. A second toast restarts the countdown, so it stays up for the full time. The Save button shows the toast Saved.

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

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Making Sound with the Web Audio API →
← Back