
Modal header
Modal body
JavaScript
// Get the modal
const modal = document.getElementById("modal");
// Get the image and insert it inside the modal
const img = document.getElementById("image-modal");
const modalImage = document.getElementById("image");
img.onclick = function() {
modal.classList.add("modal--show");
modalImage.src = this.src;
}
// Close the modal when background is clicked
modal.onclick = function(event) {
if(event.target.id !== "image") {
modal.classList.remove("modal--show");
}
}
CSS
#image-modal {
cursor: pointer;
transition: 0.3s;
}
#image-modal:hover {
opacity: 0.8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
overflow: auto;
background-color: rgba(0,0,0,0.8);
}
.modal__image {
margin: auto;
display: block;
width: 70%;
max-width: 700px;
}
.modal--show {
display: flex;
}
@media only screen and (max-width: 700px) {
.modal__image {
width: 100%;
}
}
Article code
<!-- Image to open the modal --> <img id="image-modal" src="image-url" alt="image modal"> <!-- The modal --> <div id="modal" class="modal"> <!-- The image in the modal --> <img id="image" class="modal__image"> </div>
Comments
0 comments
Please sign in to leave a comment.