Skip to content

Instantly share code, notes, and snippets.

@iankit3
Last active February 6, 2024 18:29
Show Gist options
  • Save iankit3/8e7c3d000eea49e36ae9b61c1c43aa51 to your computer and use it in GitHub Desktop.
Save iankit3/8e7c3d000eea49e36ae9b61c1c43aa51 to your computer and use it in GitHub Desktop.
import ToastNotification from "./ToastNotification.js";
document.addEventListener("DOMContentLoaded", () => {
const notification = new ToastNotification();
const toast = notification.toast.bind(notification);
window.toast = toast;
toast("Hello");
});
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Notification Toast App</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Nunito+Sans:opsz@6..12&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script type="module" src="./app.js"></script>
</body>
</html>
body {
font-family: "Nunito Sans", sans-serif;
}
div[id*="notification-container"] {
position: fixed;
display: flex;
flex-direction: column;
width: 200px;
top: 0;
margin-top: 5px;
}
div[id="notification-container-right"] {
right: 0;
}
.notification-toast {
margin-bottom: 5px;
background: #fcfea6;
padding: 0.4em 0.8em;
border: 0;
border-radius: 2px;
font-size: 1.3em;
box-shadow: -3px 3px 10px 0px #222;
}
class ToastNotification {
constructor() {
//
}
#defaultConfig = {
hPosition: "right",
vPosition: "top",
autohide: true,
timeout: 4000,
};
static GetExistingContainer(hPosition) {
return document.getElementById(`notification-container-${hPosition}`);
}
static GetContainer(hPosition) {
return (
ToastNotification.GetExistingContainer(hPosition) ||
(() => {
const elem = document.createElement("div");
elem.classList.add("notification-container");
elem.setAttribute("id", `notification-container-${hPosition}`);
document.body.appendChild(elem);
return elem;
})()
);
}
toast(message, config) {
this.config = { ...this.#defaultConfig, ...config };
const { hPosition, vPosition, timeout, autohide } = this.config;
const container = ToastNotification.GetContainer(hPosition);
const elem = document.createElement("div");
elem.classList.add("notification-toast");
elem.innerText = message;
if (autohide) {
const tmRef = setTimeout(() => {
elem.remove();
clearTimeout(tmRef);
}, timeout);
}
container.appendChild(elem);
}
}
export default ToastNotification;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment