Toasts

Published:

The toasts that are common in many web applications, they the small alerts that pops whenever something notifiable is done such gaining experience points.

In this article I use the classes as defined in Bootstrap.

https://getbootstrap.com/docs/5.0/components/toasts/.

The Toast Container

Usually you want to be as generic as possible meaning that multiple toasts can exist, for this reason we should add a container and append elements inside it.

<div class="toast-container"></div>

Then we need a function that creates the toast itself

/**
* Creates and appends a toast to toast container.
*
* @param {Toast} event should contain the content
* @listens Toast
*/
const handleToastCreate = (event) => {
  const toastContainer = document.querySelector(".toast-container")
  const toast = document.createElement('div')
  toast.classList.add('toast')
  toast.textContent = event.detail.textContent
  toastContainer.append(toast)

  // Here we can keep adding event listener to close the toast.
}

const toastContainer = document.querySelector(".toast-container")
toastContainer.addEventListener('toast', handleToastCreate)

And a function to emit an event anywhere in the app.

The Event

Any component should then be able to create a toast.

const createToast = (message) => {
  const event = new Event('toast', {detail: {
    textContent: message
  }})
  const toastContainer = document.querySelector(".toast-container")
  toastContainer.dispatchEvent(event)
}