About
This article shows you how to create a lightbox with bootstrap
The modal lightbox is a box centered with a dark background and with an image as content. It is not shown at first (or not present in the DOM at first). The user needs to click on a link to open it up.
Steps by step
Add the bootstrap resources to your page
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
Add the HTML
The lightbox is hidden until the user clicks on the image.
<div class="modal" id="lightBoxModalId" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="max-width: fit-content;">
<div class="modal-content">
<div class="modal-body" style="padding: 0">
<button type="button" class="close-media" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<img src="/_media/web/css/surfer-in-the-see-200h.png">
</div>
</div>
</div>
</div>
Style it as you want: Close button in the top right
A little bit of css to locate the close button in the top right corner of the lightbox.
.close-media {
background-color: transparent;
border: 0;
font-size: 1.5rem;
font-weight: 700;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
opacity: .5;
position: absolute;
right: 2px;
top: 2px;
}
Add the original image
The image shown is small (200px) and is wrapped in a link that will open the lightbox when clicked
<a class="lightbox" href="/_media/web/css/surfer-in-the-see-200h.png">
<img src="/_media/web/css/surfer-in-the-see-200h.png" width="200"/>
</a>
Add the code to open the lightbox on click
The javascript will show the lightbox when clicking on the image link.
document.querySelectorAll(".lightbox").forEach((lightBoxAnchor) => {
lightBoxAnchor.addEventListener("click", async function (event) {
event.preventDefault();
let lightBoxElement = document.getElementById('lightBoxModalId');
let lightBoxModal = bootstrap.Modal.getOrCreateInstance(lightBoxElement);
lightBoxModal.toggle();
});
});
Result
Click on the image to see the lightbox.