Gallery with description modals
HTML
<h1>Gallery with description modals</h1>
<p>Click a Pikachu to see his description.</p>
<ul id="gallery">
<li><img class="thumbnail" src="https://archives.bulbagarden.net/media/upload/4/4a/0025Pikachu.png" data-art-id="normal-pikachu" /></li>
<li><img class="thumbnail" src="https://archives.bulbagarden.net/media/upload/b/b6/0025Pikachu-Hoenn_Cap.png" data-art-id="cap-pikachu" /></li>
</ul>
<!-- This modal pops up to show the art description.
There is only one, which gets reused. -->
<div id="modal">
<div id="modal__box">
<div id="modal__description"></div>
<button id="modal__close">Close description</button>
<div>
</div>
<!-- The following templates contain the art descriptions.
These won't render until they're needed, so you can have a lot of them without affecting performance.
-->
<template id="normal-pikachu-desc">
<h2>Normal Pikachu</h2>
<p>This Pikachu has <em>no</em> cap!</p>
</template>
<template id="cap-pikachu-desc">
<h2>Cap Pikachu</h2>
<p>This Pikachu <em>does</em> have a cap! Wow!</p>
</template>
CSS
#modal {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 9999;
background: rgba(0,0,0,0.2);
display: none;
& #modal__box {
background: white;
padding: 3em;
margin: 5em;
}
}
.thumbnail {
height: 10em;
cursor: pointer;
border: 1px solid white;
&:hover {
border: 1px solid blue;
}
}
#gallery {
display: flex;
gap: 1em;
list-style: none;
}
JavaScript
const modal = document.getElementById('modal');
const modalDescriptionContainer = document.getElementById('modal__description');
const modalClose = document.getElementById('modal__close');
// Attach an event listener to every thumbnail to open the modal and update its content
for (const thumbnail of document.getElementsByClassName('thumbnail')) {
thumbnail.addEventListener('click', event => {
// Figure out which description we need, based on the thumbnail's data-art-id attribute
const artId = event.target.dataset.artId;
const descriptionTemplateId = artId + '-desc';
// Find the description's template by id, and import its content
const descriptionTemplate = document.getElementById(descriptionTemplateId);
const description = document.importNode(descriptionTemplate.content, true);
// Clear the modal's description area, then insert the imported content
modalDescriptionContainer.innerHTML = '';
modalDescriptionContainer.appendChild(description);
// Make the modal appear
modal.style.display = 'block';
})
}
// Make the modal disappear when the close button is clicked
modalClose.addEventListener('click', () => {
modal.style.display = 'none';
});