open modal in image list

1 min read

"Open modal" means displaying a pop-up window (modal) that appears on top of the page content and its often used to focus the user’s attention on something important, like a larger version of an image.
how to open modal
1) add imgModal
that will be toggled visible and invincible
<div id="imgModal" class="modal-image-container">
<span id="closeModal" class="close-modal">×</span>
<img id="modalImg" src="" alt="" class="modal-image">
</div>
2) for every image, if it was clicked it will show the modal
document.querySelectorAll('.image-grid img').forEach(img => {
img.addEventListener('click', function () {
document.getElementById('modalImg').src = this.src;
document.getElementById('modalImg').alt = this.alt;
document.getElementById('imgModal').style.display = 'flex';
});
});
3) if closeModal
button are clicked the modal will disappear
document.getElementById('closeModal').onclick = function () {
document.getElementById('imgModal').style.display = 'none';
};
4) if this
(background) of the image are clicked the modal will disappear
document.getElementById('imgModal').onclick = function (e) {
if (e.target === this) this.style.display = 'none';
};
You're all set!
now you can make the user focus on one image by clicking on it
Codepen
a
0
Subscribe to my newsletter
Read articles from wisnu bayu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
