A toast is the small message that slides in — "Saved!", "Message sent", "Something went wrong" — and disappears on its own. Every app needs one, and building it teaches you dynamic DOM creation, timers, and stacking. Here is a complete system you can drop into any project.
The plan
- A container fixed to the corner of the screen.
- A
showToast(message, type)function any part of your app can call. - Three types: success, error, and info, each with its own colour.
- Each toast removes itself after a few seconds, with a close button for the impatient.
The HTML
<div id="toasts"></div>
<button onclick="showToast('Saved successfully!', 'success')">Save</button>
<button onclick="showToast('Something went wrong.', 'error')">Fail</button>
The CSS
#toasts {
position: fixed;
bottom: 20px;
right: 20px;
display: flex;
flex-direction: column;
gap: 10px;
z-index: 1000;
}
.toast {
padding: 12px 16px;
border-radius: 8px;
color: white;
display: flex;
gap: 12px;
align-items: center;
animation: slideIn 0.3s ease;
}
.toast.success { background: #16a34a; }
.toast.error { background: #dc2626; }
.toast.info { background: #2563eb; }
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
The JavaScript
function showToast(message, type = 'info', duration = 3000) {
const container = document.getElementById('toasts');
const toast = document.createElement('div');
toast.className = 'toast ' + type;
const text = document.createElement('span');
text.textContent = message;
const close = document.createElement('button');
close.textContent = '✕';
close.addEventListener('click', () => removeToast(toast));
toast.append(text, close);
container.appendChild(toast);
const timer = setTimeout(() => removeToast(toast), duration);
function removeToast(el) {
clearTimeout(timer);
el.style.opacity = '0';
el.style.transition = 'opacity 0.3s';
setTimeout(() => el.remove(), 300);
}
}
Three details beginners miss
- Cap the stack. If something goes wrong in a loop, fifty toasts will bury the screen. Keep at most three or four — remove the oldest when a new one arrives:
const container = document.getElementById('toasts');
while (container.children.length >= 4) {
container.firstChild.remove();
}
-
Clear the timer when the user closes early. Without
clearTimeout, a manually closed toast tries to remove itself twice. It is harmless here, but in a bigger app that double-remove is exactly the kind of bug that wastes an afternoon. -
Use
textContent, notinnerHTML, for the message. A toast that renders raw HTML is an injection hole. The message is text — treat it as text.
What to add next
A progress bar showing how long until the toast disappears, an action button inside the toast ("Undo"), and a queue so toasts never overlap when many arrive at once.
Top comments (0)