Skip to content

Toast — JavaScript

The live example and variants are on the HTML & CSS page. This page covers driving it.

Initialize

ts
import { Toast } from '@popovandrii/ui-elements'
import '@popovandrii/ui-elements/style.css'

const toast = new Toast({ position: 'top-right', duration: 4000 })

Config: position and duration in ms (false = sticky).

Show toasts

ts
toast.success('Saved successfully')
toast.danger('Something went wrong')
toast.info('Heads up')
toast.warning('Low disk space')
toast.primary('Just so you know')

// Generic, with per-toast options:
const id = toast.show('Sticky — close manually', { duration: false })

// Per-toast options also include `timestamp`, `html`, `closable`.
toast.show('<strong>Done</strong>', { html: true })

Manage

ts
toast.dismiss(id) // close one by the id returned from show()
toast.clear()     // close all
toast.destroy()   // remove the container + listeners (e.g. onUnmounted)

Positions

position is set once, on the manager — it renders into a single fixed container. To show toasts from different corners/edges, create one manager per position:

ts
import { Toast, type ToastPosition } from '@popovandrii/ui-elements'

const managers = new Map<ToastPosition, Toast>()
const at = (p: ToastPosition) =>
  (managers.get(p) ?? managers.set(p, new Toast({ position: p })).get(p)!)

at('top-left').info('Top left')
at('bottom-center').success('Bottom center')

Events

Each toast bubbles ui-toast-show / ui-toast-dismiss:

ts
document.addEventListener('ui-toast-dismiss', (e) => {
  const { id } = (e as CustomEvent).detail
})

Usage with Vue

Create the manager in onMounted, call methods on @click, and destroy() in onUnmounted:

vue
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { Toast } from '@popovandrii/ui-elements'
import '@popovandrii/ui-elements/style.css'

let toast: Toast | null = null

onMounted(() => {
  toast = new Toast({ position: 'top-right' })
})
onUnmounted(() => toast?.destroy())
</script>

<template>
  <button type="button" @click="toast?.success('Saved')">Save</button>
</template>

One instance for the whole app

Create the Toast once (e.g. a useToast() composable) and reuse it everywhere.