Skip to content

Instantly share code, notes, and snippets.

@tgroshon
Created March 24, 2023 13:51
Show Gist options
  • Save tgroshon/4c352181a7da9bb93c2e64c9a3b18478 to your computer and use it in GitHub Desktop.
Save tgroshon/4c352181a7da9bb93c2e64c9a3b18478 to your computer and use it in GitHub Desktop.
Simple Lightbox-style Photo Gallery
const galleryItems = document.querySelectorAll(".gallery-item");
const lightbox = document.querySelector(".lightbox");
const lightboxImg = document.querySelector(".lightbox img");
const closeBtn = document.querySelector(".close-btn");
let index;
// Add click event listeners to all gallery items
galleryItems.forEach((item, i) => {
item.addEventListener("click", () => {
index = i;
lightboxImg.src = item.querySelector("img").src;
lightboxImg.alt = item.querySelector("img").alt;
lightbox.style.display = "block";
});
});
// Add click event listener to close button
closeBtn.addEventListener("click", () => {
lightbox.style.display = "none";
});
// Add keyboard event listener to navigate gallery
document.addEventListener("keydown", (e) => {
if (lightbox.style.display === "block") {
if (e.key === "ArrowLeft" && index > 0) {
index--;
lightboxImg.src = galleryItems[index].querySelector("img").src;
lightboxImg.alt = galleryItems[index].querySelector("img").alt;
} else if (e.key === "ArrowRight" && index < galleryItems.length - 1) {
index++;
lightboxImg.src = galleryItems[index].querySelector("img").src;
lightboxImg.alt = galleryItems[index].querySelector("img").alt;
}
}
});
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 20px auto;
}
.gallery-item {
margin: 10px;
}
.gallery-item img {
width: 200px;
height: 200px;
object-fit: cover;
cursor: pointer;
}
.lightbox {
display: none;
position: fixed;
z-index: 9999;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
}
.lightbox-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 80%;
max-height: 80%;
overflow: auto;
text-align: center;
}
.lightbox-content img {
width: 100%;
}
.close-btn {
position: absolute;
top: 0;
right: 0;
font-size: 30px;
font-weight: bold;
color: #fff;
cursor: pointer;
}
@tgroshon
Copy link
Author

In this implementation, clicking on a gallery item opens a lightbox-style overlay containing a larger version of the image. The user can navigate between images using the left and right arrow keys on their keyboard, and can close the lightbox.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment