Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created February 20, 2016 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save podhmo/3e6d4313129e4aacb6c9 to your computer and use it in GitHub Desktop.
Save podhmo/3e6d4313129e4aacb6c9 to your computer and use it in GitHub Desktop.
.container {
padding: 3rem;
}
.js-hide {
display: none;
}
.modal-overlay {
position: fixed;
z-index: 1;
top: 0px;
left: 0px;
height: 120%;
width: 100%;
background: rgba(0,0,0,0.8);
}
.modal {
position: fixed;
z-index: 2;
background: #fff;
}
.modal--center {
top: 25%;
left: 25%;
width: 50%;
max-height: 50%;
}
.modal.message-box {
padding: 2rem;
border: solid #aaa 1px;
border-radius: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/layout.css">
<link rel="stylesheet" href="./css/modal.css">
</head>
<body>
<section class="container">
<button data-target="#myModal" data-overlay="true">open modal(with overlay)</button>
<button data-target="#myModal">open modal</button>
<section class="js-hide modal modal--center message-box" id="myModal">
<h1>this is my modal</h1>
<p>hello this is my modal.</p>
<button data-target="#myModal">OK</button>
</section>
</section>
<script>
document.addEventListener('modal.overlay.show', function(e){
var overlay = document.createElement('div');
overlay.classList.add('modal-overlay');
document.body.appendChild(overlay)
});
document.addEventListener('modal.overlay.hide', function(e){
document.querySelector('.modal-overlay').remove();
});
document.querySelector('.container').addEventListener('click', function(e){
if(!(e.target.localName === 'button' && e.target.dataset.target)) {
return;
}
var modal = document.querySelector(e.target.dataset.target);
var overlay = e.target.dataset.overlay;
if (modal.classList.contains('js-hide')) {
if (overlay) {
document.dispatchEvent(new CustomEvent('modal.overlay.show', {}));
}
modal.classList.remove('js-hide');
} else {
document.dispatchEvent(new CustomEvent('modal.overlay.hide', {}));
modal.classList.add('js-hide');
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment