Author: | Chris Pennington |
---|---|
Views Total: | 925 views |
Official Page: | Go to website |
Last Update: | May 16, 2022 |
License: | MIT |
Preview:

Description:
A toast message is an alert displayed for a short period of time in a web page or app.
This article will explore how we can now create these types of notification messages using plain JavaScript and CSS, as well as explore how we can make the toast messages animated and stackable.
How to use it:
1. The main function for toast messages. Copy and paste the following JS snippets into your app and don’t forget to override the default background color, text color, and timeout as follows:
let toastContainer; function generateToast({ message, // override the default styles here background = '#00214d', color = '#fffffe', length = '3000ms', }){ toastContainer.insertAdjacentHTML('beforeend', `<p class="toast" style="background-color: ${background}; color: ${color}; animation-duration: ${length}"> ${message} </p>`) const toast = toastContainer.lastElementChild; toast.addEventListener('animationend', () => toast.remove()) }
2. Initialize the toast function and inject the necessary CSS styles into the document.
(function initToast(){ document.body.insertAdjacentHTML('afterbegin', `<div class="toast-container"></div> <style> .toast-container { position: fixed; top: 1rem; right: 1.5rem; display: grid; justify-items: end; gap: 1.5rem; } .toast { font-size: 1.5rem; font-weight: bold; line-height: 1; padding: 0.5em 1em; background-color: lightblue; animation: toastIt 3000ms cubic-bezier(0.785, 0.135, 0.15, 0.86) forwards; } @keyframes toastIt { 0%, 100% { transform: translateY(-150%); opacity: 0; } 10%, 90% { transform: translateY(0); opacity: 1; } } </style> `); toastContainer = document.querySelector('.toast-container'); })()
3. Display a toast message on the page.
generateToast({ message: "✍️ Write this down… ✍️", background: "hsl(51 97.8% 65.1%)", color: "hsl(51 97.8% 12.1%)", length: "8000ms", });