TLDR - There's a native HTML <dialog> popup box. No need to load "plugins" and "frameworks" for simple projects.
(1) BASIC DIALOG BOX
<dialog id="ezpop"><form method="dialog">
<div id="eztxt">Hello!</div>
<button id="ezclose">X</button>
</form></dialog>
<button onclick="document.getElementById('ezpop').showModal()">
Show
</button>
-
<div id="eztxt">Text you want to show. -
<button id="ezclose">Close popup button. -
<form method="dialog">Necessary to registerezcloseas a "close button". - Use
showModal()to open the dialog box.
(2) POPUP JS WIDGET
var pop = {
// (A) CREATE POPUP DIALOG BOX
dialog : null, // dialog box wrapper
txt : null, // dialog box text area
init : () => {
pop.dialog = document.createElement("dialog");
pop.dialog.id = "ezpop";
pop.dialog.innerHTML = `<form method="dialog">
<div id="eztxt"></div>
<button id="ezclose">X</button>
</form>`;
pop.txt = pop.dialog.querySelector("#eztxt");
document.body.appendChild(pop.dialog);
},
// (B) SHOW DIALOG BOX
show : txt => {
pop.txt.innerHTML = txt;
pop.dialog.showModal();
}
};
window.addEventListener("load", pop.init);
With that, let us turn the above "simple dialog box" into a "reusable widget" with JS.
- (A) On window load, call
pop.init(). - (A) This will create and insert the above
<dialog>into the page. - (B) Self-explanatory.
pop.show(TEXT)will placeTEXTintoeztxtand show the dialog box.
(3) CUSTOM CSS
/* (A) POPUP WRAPPER */
#ezpop {
display: block;
min-width: 400px; padding: 20px;
border: 0; border-radius: 10px;
background: #fff;
opacity: 0;
transition: opacity 0.5s;
}
#ezpop[open] { opacity: 1; }
/* (B) CLOSE BUTTON */
#ezclose {
position: absolute; top: 0; right: 0;
margin: 5px; padding: 0;
font-size: 30px; font-weight: 700;
color: #cd2f2f; background: none; border: none;
cursor: pointer;
}
#ezclose:focus { outline: none; }
/* (C) BACKGROUND COLOR */
#ezpop::backdrop {
background: rgba(0, 0, 0, 0.5);
}
Completely optional, but if you want to customize the popup dialog box - We can.
- (A) Set the dimensions and colors. We can also control the open/close animations using CSS
transition. - (B) Place the close button at the top-right corner.
- (C) Set the color of the backdrop (fullscreen blackout).
THE END
That's all for this super short sharing. Here are some links to the GIST, YouTube Tutorial, and original blog post.
Top comments (0)