I have posted an article on implementing a Modal in pure Javascript here : VanillaModal.
But I don't like to have functions pollute global namespace.
With µhtml you can wrap your code in an IIFE and it just works.
You can test it here : UHTMLModal
<div id="modal"></div>
<div>
<h1>Modal with UHTML</h1>
<div id="triggerModal">
<button modal="legal" >
Legal
</button>
<button modal="news" >
News
</button>
<button modal="about" >
About
</button>
</div>
</div>
#modal{
}
.modal-shown {
display: block;
}
.modal-hidden {
display: none;
}
.modal {
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(222,0,0);
background-color: rgba(2,0,0,0.5);
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 960px;
position:relative;
animation:animetop 0.4s
}
@keyframes animetop{
from{top:-300px;opacity:0}
to{top:0;opacity:1
}
}
.modal-close {
cursor: pointer;
right:0;
}
.modal-close:hover {
box-shadow: 0 0 5px rgba(0,0,0,0.4);
}
import {render, html} from 'uhtml';
(function () {
let Contents = {
"legal" : html`<h1>Legal</h1>`,
"news" : html`<h1>News</h1>`,
"about" : html`<h1>About</h1>`
}
let State = {
content: "",
isOpen: false,
openDialog () {
State.content = this.content
State.isOpen = true;
view()
},
closeDialog () {
State.isOpen = false;
view();
}
}
function view () {
var modalCls = State.isOpen
? "modal modal-shown"
: "modal modal-hidden"
render(modal, html`
<div class="${modalCls}">
<div class="modal-content">
<div style="text-align:right" onclick = ${State.closeDialog}>
<span class="modal-close">Close</span>
</div>
<p>${State.content}</p>
</div>
</div>
`)
}
triggerModal.addEventListener("click", function (e) {
let modalName = e.target.getAttribute("modal")
State.content = Contents[modalName]
modalName && State.openDialog(modal)
})
})()
Top comments (0)