Minimal Snackbar UI Component In Vanilla JavaScript

Category: Javascript , Notification | September 7, 2021
Author:ArslanAmeer
Views Total:103 views
Official Page:Go to website
Last Update:September 7, 2021
License:MIT

Preview:

Minimal Snackbar UI Component In Vanilla JavaScript

Description:

A minimal, modern snackbar notification popup that works with Javascript Promises.

How to use it:

1. Add your own notification message to the snackbar.

<div class="snackbar-wrapper">
  <div class="snackbar">
    <img src="notification.svg" alt="notification-icon">
    <p>This is a SanckBar Notification !</p>
  </div>
</div>

2. Create a button to trigger the snackbar notification.

<button type="button" class="btn">Click To Reveal Snackbar</button>

3. The main script to enable the button to toggle the snackbar notification.

"use strict";
var btn = document.querySelector(".btn");
var bar = document.querySelector(".snackbar-wrapper");
btn.addEventListener("click", () => {
    btn.disabled = true;
    showPromise().then(setTimeout(() => {
        hidePromise().then(() => {
            btn.disabled = false;
        });;
    }, 3000));
});
var showPromise = () => {
    return new Promise((resolve, reject) => {
        bar.style.display = "inline-block";
        setTimeout(() => {
            bar.style.opacity = 1;
            bar.style.top = "90vh";
            resolve();
        }, 10);
    });
}
var hidePromise = () => {
    return new Promise((resolve, reject) => {
        bar.style.opacity = 0;
        bar.style.top = "110vh";
        setTimeout(() => {
            bar.style.display = "none";
            resolve();
        }, 500);
    });
}

4. The example CSS for the snackbar.

.snackbar-wrapper{
  display: none;
  border-radius: 5px;
  background-color: rgba(0, 0, 0, 0.9);
  padding: 15px;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  color: white;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  position: fixed;
  top: 110vh; left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: top .5s ease-in-out, opacity .7s ease-in-out;
}
.snackbar{
  display: flex;
  justify-content: space-evenly;
}
.snackbar > img{
  width: 20px;
  margin-right: 10px;
}
.snackbar > p{
  padding: 0; margin: 0;
}

You Might Be Interested In:


Leave a Reply