Simple toast element with vanilla js and animation effects
Tutorial by Mirko Zovko | 20. Jul. 2020.
How to create simple toast element with vanilla js
Welcome to one more tutorial in series of creating simple elements with vanilla js. In this tutorial I’ll show you how to create a simple toast element with different style and show animation effects.
This tutorial is a bit more complicated than the other ones but do not worry, I’ll try to explain every line of the code so you know what is what and as always if you have any question feel free to write in comment below.
First what we need to do is create structure of the toast element:
- toast-container - is main container for all toast messages
toast - is a container for one toast message, adding an active class on it becomes visible. I created also few different toast messages:
- without any class it’s white and doesn't have any icon
- system - with this class it become blue and it has material build icon
- success - with this class it become green and it has material done icon
- warning - with this class it become orange and it has material report_problem icon
- bug - with this class it become red and it has material bug_report icon
- t-title - is toast message title that can also contain icon, I used material icons in this tutorial
- t-close - is a button for closing the toast message even before end of it’s duration time
- t-text - is a text content of a toast message
- First function is checking if the dom content is loaded and checking if there is a .toast-container element, then there isn’t it creating that element at the end of the body tag. In there all the toast messages will be created
Second function createToast() is used for creating the toast element. Function receive few parameters:
- type - as I already mention it's the only style difference, and I created only a few of them: system, success, warning, and bug. You can also leave it blank, and it will be white.
- title - title text of the toast message
- text - text of the toast message
- duration - how much time is needed to disappear, duration period. If you don’t add any value, duration will have a 3000ms period, I put it as default value. But also if you add 0 as duration, toast message will not disappear
- Third one is for closing the modal on the t-close button click. With this you can close some toast messages before the duration ends.
- Last, the fourth function is a button for creating toast messages. For some element to create toats message need to have btn-toast class with datasets parameters. You can check the code example below.
You can also always create a toast message by just calling the createToast. Like that you can use toast for any kind of event you want.
I hope you liked this article. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)