Skip to content

Toast ​

Notifications built on Bootstrap Toast, with declarative triggers and a safe create() API.

  • Version 1.1.0
  • Bootstrap 5.3+
  • Requires Bootstrap CSS + Bootstrap JS bundle
  • Source on GitHub

Installation ​

bash
npx bootcn add toast
bash
pnpm dlx bootcn add toast
bash
yarn dlx bootcn add toast
bash
bunx --bun bootcn add toast

The CLI also installs the design tokens and these components: button. It prints the <link> and <script> tags to add to your layout.

Usage ​

Show an existing toast:

html
<button
  type="button"
  class="btn bootcn-button bootcn-button--outline"
  data-bootcn-toast-target="#saved"
>
  Save
</button>

<div
  class="toast-container position-fixed bottom-0 end-0 p-3 bootcn-toast-container"
  data-bootcn-toast-container
>
  <div
    class="toast bootcn-toast bootcn-toast--default"
    id="saved"
    role="status"
    aria-live="polite"
    aria-atomic="true"
  >
    <div class="bootcn-toast__body">
      <div class="bootcn-toast__text">
        <p class="bootcn-toast__title">Changes saved</p>
        <p class="bootcn-toast__description">Your profile was updated.</p>
      </div>
      <button
        type="button"
        class="btn-close bootcn-toast__close"
        data-bs-dismiss="toast"
        aria-label="Close notification"
      ></button>
    </div>
  </div>
</div>

Create one from a button, without writing JavaScript:

html
<button
  type="button"
  class="btn bootcn-button bootcn-button--outline"
  data-bootcn-toast-create
  data-bootcn-toast-title="Invitation sent"
  data-bootcn-toast-message="We emailed nikos@example.com."
  data-bootcn-toast-variant="success"
>
  Invite
</button>

Or from your own script (for example after a fetch):

js
window.Bootcn.toast.create({
  title: 'Upload failed',
  message: 'The file is larger than 10 MB.',
  variant: 'destructive', // 'default' | 'success' | 'destructive'
  autohide: true,
  delay: 5000,
});

Created toasts go into the first [data-bootcn-toast-container] (one is added at the bottom right if none exists) and are removed from the page when hidden.

From PHP, a flash message can render a toast with class="toast show ...", or print a create() call with json_encode() for the strings.

JavaScript API ​

MethodDescription
Bootcn.toast.show(el)Show an existing toast (element or selector)
Bootcn.toast.create(o)Build, show and later remove a toast; returns it
Bootcn.toast.init()Attach the delegated click handler (idempotent)
Bootcn.toast.destroy()Remove the handler

Bootstrap's own events (show.bs.toast, hidden.bs.toast, …) fire on the toast element.

Dependencies ​

  • Bootstrap 5.3+ CSS and JavaScript bundle (Toast). If it is missing, toast.js logs one console error.
  • themes/tokens/tokens.css, button (example triggers).

Accessibility ​

  • Toasts use role="status" / aria-live="polite"; destructive toasts created with create() use role="alert" / aria-live="assertive".
  • Keep messages short. Do not put the only copy of important information, or actions the user must take, in a toast that hides itself.
  • Every toast has a labelled close button. Bootstrap pauses auto-hide while the pointer or focus is on the toast and disables the fade under reduced motion.

Source ​

The exact files the CLI installs (toast@1.1.0). View on GitHub · Report an issue

html
<div class="d-flex flex-wrap gap-2">
  <button
    type="button"
    class="btn bootcn-button bootcn-button--outline"
    data-bootcn-toast-target="#bootcn-toast-saved"
  >
    Show saved toast
  </button>
  <button
    type="button"
    class="btn bootcn-button bootcn-button--outline"
    data-bootcn-toast-create
    data-bootcn-toast-title="Invitation sent"
    data-bootcn-toast-message="We emailed nikos@example.com."
    data-bootcn-toast-variant="success"
  >
    Create toast
  </button>
  <button
    type="button"
    class="btn bootcn-button bootcn-button--destructive"
    data-bootcn-toast-create
    data-bootcn-toast-title="Upload failed"
    data-bootcn-toast-message="The file is larger than 10 MB."
    data-bootcn-toast-variant="destructive"
  >
    Create error toast
  </button>
</div>

<div
  class="toast-container position-fixed bottom-0 end-0 p-3 bootcn-toast-container"
  data-bootcn-toast-container
>
  <div
    class="toast bootcn-toast bootcn-toast--default"
    id="bootcn-toast-saved"
    role="status"
    aria-live="polite"
    aria-atomic="true"
  >
    <div class="bootcn-toast__body">
      <div class="bootcn-toast__text">
        <p class="bootcn-toast__title">Changes saved</p>
        <p class="bootcn-toast__description">Your profile was updated.</p>
      </div>
      <button
        type="button"
        class="btn-close bootcn-toast__close"
        data-bs-dismiss="toast"
        aria-label="Close notification"
      ></button>
    </div>
  </div>
</div>
css
.bootcn-toast-container {
  --bootcn-toast-gap: 0.5rem;

  display: flex;
  flex-direction: column;
  gap: var(--bootcn-toast-gap);
  max-width: 100%;
}

.bootcn-toast-container > .bootcn-toast {
  margin: 0;
}

.bootcn-toast {
  --bs-toast-max-width: 22rem;
  --bs-toast-bg: var(--bootcn-background);
  --bs-toast-color: var(--bootcn-foreground);
  --bs-toast-border-color: var(--bootcn-border-color);
  --bs-toast-border-radius: var(--bootcn-radius-lg);
  --bs-toast-box-shadow: var(--bootcn-shadow-lg);
  --bs-toast-font-size: 0.875rem;

  max-width: min(var(--bs-toast-max-width), 100%);
}

.bootcn-toast--success {
  --bs-toast-border-color: var(--bs-success-border-subtle);
}

.bootcn-toast--destructive {
  --bs-toast-bg: var(--bs-danger-bg-subtle);
  --bs-toast-color: var(--bs-danger-text-emphasis);
  --bs-toast-border-color: var(--bs-danger-border-subtle);
}

.bootcn-toast__body {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  padding: 1rem;
}

.bootcn-toast__text {
  flex: 1 1 auto;
  min-width: 0;
}

.bootcn-toast__title {
  margin: 0;
  font-weight: 600;
}

.bootcn-toast__description {
  margin: 0.125rem 0 0;
  opacity: 0.85;
}

.bootcn-toast__close {
  flex-shrink: 0;
  margin-top: 0.125rem;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.toast) return; // already loaded: idempotent

  const SHOW_SELECTOR = '[data-bootcn-toast-target]';
  const CREATE_SELECTOR = '[data-bootcn-toast-create]';
  const CONTAINER_SELECTOR = '[data-bootcn-toast-container]';
  const VARIANTS = ['default', 'success', 'destructive'];
  let listening = false;

  function ensureBootstrap() {
    if (window.bootstrap && window.bootstrap.Toast) return true;
    console.error(
      '[bootcn] toast: Bootstrap JavaScript is required. Load the Bootstrap bundle (window.bootstrap.Toast) before bootcn toast.js.',
    );
    return false;
  }

  function resolve(target) {
    if (target instanceof Element) return target;
    if (typeof target === 'string') return document.querySelector(target);
    return null;
  }

  /** Shows an existing toast element (or selector). Returns the element. */
  function show(target) {
    const element = resolve(target);
    if (!element) {
      console.error('[bootcn] toast: no toast found for', target);
      return null;
    }
    if (!ensureBootstrap()) return null;
    window.bootstrap.Toast.getOrCreateInstance(element).show();
    return element;
  }

  function container() {
    let region = document.querySelector(CONTAINER_SELECTOR);
    if (!region) {
      region = document.createElement('div');
      region.className = 'toast-container position-fixed bottom-0 end-0 p-3 bootcn-toast-container';
      region.setAttribute('data-bootcn-toast-container', '');
      document.body.appendChild(region);
    }
    return region;
  }

  /**
   * Creates, shows and (when hidden) removes a toast.
   * options: { title, message, variant: 'default'|'success'|'destructive',
   *            autohide: true, delay: 5000 }
   * Text is inserted with textContent, never as HTML.
   */
  function create(options) {
    const settings = Object.assign({ variant: 'default', autohide: true, delay: 5000 }, options);
    if (!ensureBootstrap()) return null;
    const variant = VARIANTS.indexOf(settings.variant) === -1 ? 'default' : settings.variant;
    const urgent = variant === 'destructive';

    const toast = document.createElement('div');
    toast.className = 'toast bootcn-toast bootcn-toast--' + variant;
    toast.setAttribute('role', urgent ? 'alert' : 'status');
    toast.setAttribute('aria-live', urgent ? 'assertive' : 'polite');
    toast.setAttribute('aria-atomic', 'true');

    const body = document.createElement('div');
    body.className = 'bootcn-toast__body';
    const text = document.createElement('div');
    text.className = 'bootcn-toast__text';
    if (settings.title) {
      const title = document.createElement('p');
      title.className = 'bootcn-toast__title';
      title.textContent = String(settings.title);
      text.appendChild(title);
    }
    if (settings.message) {
      const message = document.createElement('p');
      message.className = 'bootcn-toast__description';
      message.textContent = String(settings.message);
      text.appendChild(message);
    }
    const close = document.createElement('button');
    close.type = 'button';
    close.className = 'btn-close bootcn-toast__close';
    close.setAttribute('data-bs-dismiss', 'toast');
    close.setAttribute('aria-label', 'Close notification');
    body.appendChild(text);
    body.appendChild(close);
    toast.appendChild(body);

    container().appendChild(toast);
    toast.addEventListener('hidden.bs.toast', function () {
      const instance = window.bootstrap.Toast.getInstance(toast);
      if (instance) instance.dispose();
      toast.remove();
    });
    window.bootstrap.Toast.getOrCreateInstance(toast, {
      autohide: Boolean(settings.autohide),
      delay: Number(settings.delay) || 5000,
    }).show();
    return toast;
  }

  function handleClick(event) {
    const target = event.target;
    if (!(target instanceof Element)) return;

    const showTrigger = target.closest(SHOW_SELECTOR);
    if (showTrigger) {
      show(showTrigger.getAttribute('data-bootcn-toast-target'));
      return;
    }

    const createTrigger = target.closest(CREATE_SELECTOR);
    if (createTrigger) {
      create({
        title: createTrigger.getAttribute('data-bootcn-toast-title'),
        message: createTrigger.getAttribute('data-bootcn-toast-message'),
        variant: createTrigger.getAttribute('data-bootcn-toast-variant') || 'default',
      });
    }
  }

  // Delegated listener on document: works for triggers added later too.
  // `root` is accepted for API consistency; init/destroy act on the document.
  function init(root = document) {
    if (!root || listening) return;
    if (!ensureBootstrap()) return;
    document.addEventListener('click', handleClick);
    listening = true;
  }

  function destroy(root = document) {
    if (!root || !listening) return;
    document.removeEventListener('click', handleClick);
    listening = false;
  }

  ns.toast = { init: init, destroy: destroy, show: show, create: create };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function () {
      init(document);
    });
  } else {
    init(document);
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.