DEV Community

loading...
Cover image for Toast Notifications with Alpine.js & Tailwind.css

Toast Notifications with Alpine.js & Tailwind.css

zaxwebs profile image Zack Webster ・1 min read

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.

Alt Text

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
    },
})
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)

pic
Editor guide