vanilla JS notification snackbar
posted on June 13, 2021, 12:00 am in
Show styled notification messages to your users the easy way, no framework required.
Code
var TIME_ON_SCREEN = 5000;
var createElementEx = function (id, className, innerHTML = '') {
var el = document.createElement('div');
el.id = id;
el.className = className;
el.innerHTML = innerHTML;
return el;
};
var notify = function (msg) {
var uid = `notify-${new Date().getTime()}`;
var exists = document.querySelectorAll('.notify');
var newEl = createElementEx(uid, 'notify');
var text = createElementEx('', 'notify-text', msg);
newEl.appendChild(text);
document.body.appendChild(newEl);
newEl.style.bottom = (25 + 65 * (exists.length)) + 'px';
setTimeout(function () {
newEl.className += ' notify-active';
}, 0);
setTimeout(function () {
newEl.className = ' notify';
}, TIME_ON_SCREEN);
setTimeout(function () {
newEl.parentNode.removeChild(newEl);
}, TIME_ON_SCREEN + 500);
};
window.notify = function (m) {
notify(m)
};
Style
.notify {
border-radius: 5px;
width: 400px;
position: fixed;
bottom: 25px;
left: 25px;
padding: 20px;
z-index: 9999;
background-color: rgba(0, 0, 0, 0);
color: rgba(0, 0, 0, 0);
text-transform: capitalize;
transition: 500ms ease-in-out;
}
.notify-active {
background: #272725;
color: #dfdfdf;
}