Toasts are messages that are displayed outside the regular flow of content to provide timely information about an event on the page. This implementation uses an ARIA live message so that the toast message is announced immediately to screen reader users. The end of the animation of the progress bar doubles as an event to trigger the removal of the toast element from the page.
An empty element is used to hold a list of toasts. The toast list element is used so that multiple toasts can be added to the page without overlapping each other.
One of the key features of this implementation is that the toast
lifecycle—from creation to to destruction—is driven by CSS animations.
This removes a great deal of complexity from the JavaScript code.
We are using the animationend
event to hook into the
lifecycle animations.
The toast messages are themselves codeed as part of the markup such
that we don't need to intermix markup and logc in JavaScript. However,
because we are using a plain <template>
element
as the basis for the messages, it is still possible to create them
on the fly in JavaScript without jumping through hoops. This can be
useful if our messages are coming from an external source such as a
backend.
Although using toasts is tempting, you should generally avoid it whenever showing feedback right next to the form control is an option. The reason for this is that some users use screen magnifiers that allows them to only see a small portion of the screen at once. For these users, toasts are usually too far outside the visible area for them to notice.