Vanilla JavaScript Projects

Project 86, Content and data

Toast Notification Center

Small messages that confirm what just happened without getting in the way. They stack neatly, pause when you hover and let people undo mistakes.

Main API
ARIA live regions
Motion
Web Animations API
Dependencies
None
Your browser
Checking

Send some toasts

Press the buttons to send toasts. Hover a toast to pause it. Try Delete a file and press Undo. Change the position and check the history.

Your app

How it works

  1. One region per positionToasts go into a container with aria-live, so screen readers announce them. Errors use role alert so they are read straight away.
  2. Timers you can pauseThe progress bar is a Web Animation. Its onfinish closes the toast, and hovering or focusing pauses it, so people have time to read.
  3. Keep the stack shortWhen the limit is reached, the oldest toast leaves first. Every toast is also saved to the history panel with a time.
function toast(title, { type = "info", duration = 5000, undo } = {}) {
  const el = document.createElement("div");
  el.setAttribute("role", type === "error" ? "alert" : "status");
  el.innerHTML = `<b>${title}</b>${undo ? "<button>Undo</button>" : ""}<span class="bar"></span>`;
  region.append(el);
  const bar = el.querySelector(".bar").animate(
    [{ transform: "scaleX(1)" }, { transform: "scaleX(0)" }], { duration });
  bar.onfinish = () => el.remove();
  el.onpointerenter = () => bar.pause();
  el.onpointerleave = () => bar.play();
}