All links with the class name "modal-link" will open in the pop-up window
<!DOCTYPE html>
<html>
<head>
<title>Modals</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="page">
<h1>Modals part 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
<a href="#message1" class="modal-link" >Click here!</a>
<p>Ut euismod sapien massa, a pulvinar metus condimentum in...</p>
<a href="#message2" class="modal-link" >Click here as well!</a>
<p>Sed auctor malesuada quam...</p>
<p>Fusce vel ipsum eu sem consectetur dignissim at in orci..</p>
<a href="#message1" class="modal-link" >Click here as well!</a>
</div>
<div class="modal-messages" style="display:none;">
<span id="message1">This is message 1<br/><strong>Some text in bold</strong></span>
<span id="message2">This is message 2</span>
</div>
<!--Elements for the overlay screen-->
<div class="overlay-outer" id="overlay-outer">
<div class="overlay-inner" id="overlay-inner">
<div class="overlay-content" id="overlay-content">
<p class="modal-string" id="modal-string">Modal content goes here</p>
<button class="close-btn" id="close-btn" title="Close window">X</button>
</div>
</div>
</div>
</body>
</html>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
p{
margin: 10px 0;
}
.page{
max-width: 700px;
margin:20px auto;
}
.overlay-outer{
display: none;
position:fixed;
top: 0;
left: 0;
width:100%;
height:100%;
background: rgba(256,256,256,0.8);
}
.overlay-inner{
display:table-cell;
vertical-align:middle;
text-align:center;
}
.overlay-content{
display:inline-block;
background:#eee;
box-shadow: 1px 1px 3px #444;
padding: 1rem;
position:relative;
}
.close-btn{
position:absolute;
right: -10px;
top: -10px;
padding:5px 8px;
background:#111;
color:#fff;
border:none;
cursor:pointer;
}
function pageLoad () {
//Handler functions for the events
function openModal (event) {
event.preventDefault ();
modalString.innerHTML = document.querySelector(this.getAttribute('href')).innerHTML;
overlayOuter.style.display = 'table';
}
function closeModal () {
modalString.innerHTML = '';
overlayOuter.style.display = 'none';
}
//Reference the DOM elements
var overlayOuter = document.getElementById('overlay-outer');
var modalString = document.getElementById('modal-string');
var closeOverlay = document.getElementById('close-btn');
var modalLinks = document.querySelectorAll('.modal-link');
//Attach eventlisteners to the elements
for (var i = 0; i < modalLinks.length; i++){
modalLinks[i].addEventListener('click', openModal, false);
}
closeOverlay.addEventListener('click', closeModal, false);
}
window.addEventListener('load', pageLoad);