Toast notifications are notifications that silently pop up and fade away. They can be used to indicate events and their status such as if a document was saved successfully.
Recently, I implemented a basic "toaster" using Alpine.js and Tailwind.css.
You can try it out live here: Toaster Demo
Features
- "Hook" to create toasts from anywhere - uses Spruce for global state access.
- Auto-close after a set interval.
- Close on click.
- Stack toasts if more than one.
- Easy to expand.
Implementation
The following code is what powers the toast system:
Spruce.store("toasts", {
counter: 0,
list: [],
createToast(message, type = "info") {
const index = this.list.length
let totalVisible = this.list.filter((toast) => {
return toast.visible
}).length + 1
this.list.push({
id: this.counter++,
message,
type,
visible: true,
})
setTimeout(() => {
this.destroyToast(index)
}, 2000 * totalVisible)
},
destroyToast(index) {
this.list[index].visible = false
},
})
Well, this and the HTML that consumes it.
You can have a look at the full source code here: GitHub Repo
What's Next?
One can add a whole ton of functionality quite easily. Here are a few examples:
- Close-all button.
- History
- Headings and more.
- Scrolling
That's all for this article. Thanks so much for reading.
I publish one article every week, if you'd like to see more of my content consider subscribing.
Have a great day.
Top comments (6)
Zack this is such a great resource, together with all the other tailwind+alpine examples in your repo. Really nice.
It would be nice if there was a little more context as to why we need Spruce, but maybe it will become more clear as I dig in. :)
Thank you for your words, David.
About Spruce, I have it for this as I'd like the ability to invoke the toasts from anywhere. So, a global state management solution seemed like a good idea.
My understanding is this is a core part of Alpine 3. So maybe this and other examples youβve made could see Spruce being phased out. π€βΊοΈ
Alpine 3 came out about 3 months after this post.
But yeah, if I were to redo these now, I'd definitely go with core.
Wow this is so perfect exactly what I'm looking for! Thanks so much.
Update: I'd like to quantify what I love about this example. It's a MVP "that just works". It uses native libraries. The code is readable. In a nutshell, it's short, and it's sweet.
Glad to be of help, Eugene.