<h1>Material Snackbar Example using Alpine.Js</h1>
<button onclick="showAlpineSnackbar()" class="button">Show Snackbar</button>
<h2>Click on the above button to see snackbar message</h2>
<div x-data="alpineSnackbar()" x-init="init()" x-show.transition="show" class="alpine-snackbar-wrapper">
  <div class="alpine-snackbar-content" x-text="message"></div>
</div>
body {
  font-family: "Roboto", sans-serif;
}

.alpine-snackbar-wrapper {
  min-width: 344px;
  max-width: 672px;
  min-height: 48px;
  background-color: #2196f3;
  color: #fff;
  text-align: center;
  margin: auto 8px;
  display: flex;
  align-items: center;
  padding: 0;
  border-radius: 4px;
  position: fixed;
  right: 1%;
  z-index: 1;
  bottom: 30px;
  box-shadow: 0 3px 5px -1px rgba(0, 0, 0, 0.2),
    0 6px 10px 0 rgba(0, 0, 0, 0.14), 0 1px 18px 0 rgba(0, 0, 0, 0.12);
}

.alpine-snackbar-content {
  flex-grow: 1;
  font-size: 0.875em;
  font-weight: 400;
  padding: 14px 16px;
}

.button {
  border: none;
  padding: 14px 16px;
  border-radius: 4px;
  font-size: 1em;
  background-color: #2196f3;
  color: white;
  cursor: pointer;
}
function showAlpineSnackbar() {
  let event = new CustomEvent("alpine-snackbar-showMessage", {
    detail: {
      message: "Hello from outside of the component"
    }
  });
  window.dispatchEvent(event);
}

function alpineSnackbar() {
  return {
    show: false,
    message: null,
    init() {
      window.addEventListener("alpine-snackbar-showMessage", (event) => {
        this.showMessage(event.detail.message);
      });
    },
    showMessage(msg) {
      this.message = msg;
      this.show = true;
      window.setTimeout(() => {
        this.show = false;
        this.message = null;
      }, 2000);
    }
  };
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.8.0/alpine.js