code everywhere

vanilla JS notification snackbar

posted on June 13, 2021, 12:00 am in js

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;
}

Demo

Open Notification

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy