simple-popup-js
Version:
Zero-HTML confirm popup that injects its own DOM and CSS. Tiny, framework-free.
34 lines • 2.12 kB
JavaScript
(function(){
function injectStyles(){
if (document.getElementById('popup-style')) return;
var style = document.createElement('style');
style.id = 'popup-style';
style.textContent = ".customPopup{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.6);z-index:9999;text-align:center;opacity:0;transition:opacity .2s ease}.popupBody{background:#fff;display:inline-block;margin-top:15%;padding:20px;border-radius:8px;min-width:300px}.popupBody>p{margin-bottom:20px}.btn{padding:6px 12px;border-radius:4px;border:0;cursor:pointer}.btn-success{background:#28a745;color:#fff}.btn-warning{background:#ffc107;color:#000}";
document.head.appendChild(style);
}
function createDOM(){
if (document.getElementById('customPopup')) return;
var popup = document.createElement('div');
popup.id = 'customPopup';
popup.className = 'customPopup';
popup.innerHTML = '<div class="popupBody"><p id="confirmMessage"></p><button id="confirmYes" class="btn btn-sm btn-success">Yes</button><button id="confirmNo" class="btn btn-sm btn-warning">No</button></div>';
document.body.appendChild(popup);
}
function ensureReady(){ injectStyles(); createDOM(); }
function fadeIn(el){ el.style.display='block'; requestAnimationFrame(function(){ el.style.opacity='1'; }); }
function fadeOut(el){ el.style.opacity='0'; setTimeout(function(){ el.style.display='none'; }, 200); }
window.customPopup = function(message, onYes, onNo){
ensureReady();
var popup = document.getElementById('customPopup');
var msg = document.getElementById('confirmMessage');
var yesBtn = document.getElementById('confirmYes');
var noBtn = document.getElementById('confirmNo');
msg.innerHTML = message;
fadeIn(popup);
var y2 = yesBtn.cloneNode(true);
var n2 = noBtn.cloneNode(true);
yesBtn.replaceWith(y2); noBtn.replaceWith(n2);
y2.addEventListener('click', function(){ fadeOut(popup); if (typeof onYes === 'function') onYes(); });
n2.addEventListener('click', function(){ fadeOut(popup); if (typeof onNo === 'function') onNo(); });
};
})();