Lightbox Image with Vanilla Javascript

Elevate your web design with a Vanilla JavaScript lightbox image gallery. Learn how in our step-by-step tutorial!

In today's web development world, creating elegant and user-friendly interfaces is a top priority. One way to significantly enhance user experience on your website is by implementing a lightbox image feature. A lightbox allows you to display images in a distraction-free overlay, making it a favorite choice for showcasing galleries or large images. In this tutorial, we'll guide you through the process of creating a custom lightbox image using vanilla JavaScript, allowing you to integrate it seamlessly into your own webpage.

Styling

Add the following CSS:

/*! Image Lightbox CSS
 * Copyright: Deo Kumar - Fineshop Design
 * License: MIT
 */
.lbImg{position:relative}
.lbImg::before{content:'';position:absolute;top:10px;right:5px;width:30px;height:30px;display:flex;margin:0 5px;background: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23363637' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3'/></svg>") center / 14px no-repeat;background-color:rgba(0,0,0,.2);border-radius:50%;z-index:2;opacity:0;transition:all 0.2s ease;cursor:pointer}
.lbImg:hover::before{opacity:1}
.lbImg img {cursor:zoom-in;}
.zmImg{position:fixed;top:0;left:0;bottom:0;right:0;background:rgba(0,0,0,0.75);display:flex;align-items:center;justify-content:center;z-index:999;-webkit-backdrop-filter:saturate(180%) blur(15px);backdrop-filter:saturate(180%) blur(15px);opacity:0;visibility:hidden;transition:all 0.4s ease;}
.zmImg.active{opacity:1;visibility:visible}
.zmImg a, .zmImg a:hover{opacity:1}
.zmImg img{display:block;max-width:92%;max-height:92%;width:auto;margin:auto;border-radius:10px;box-shadow:0 5px 30px 0 rgba(0,0,0,.05);transform:scale(0.4);transition:all 0.4s ease;transition-property:transform;}
.zmImg.active img {transform:scale(1);cursor:zoom-out;}
.zmImg img.full{left:auto;right:auto;border-radius:10px;width:auto}
.zmImg::after{content:'\2715';line-height:16px;font-size:14px;color:#fffdfc;background:#482dff;position:fixed;bottom:-20px;right:-20px; display:flex;align-items:center;justify-content:center;width:45px;height:45px;border-radius:50%;opacity:0;visibility:hidden;transition:all 0.4s ease;}
.zmImg.active::after{bottom:20px;right:20px;opacity:1;visibility:visible;cursor:pointer}

To ensure your lightbox matches your website's design, make sure to add your custom CSS styles. You can style the lightbox container, close button, and any other elements as needed to create a cohesive and visually pleasing experience.

JavaScript Magic

Now, let's dive into the JavaScript code to make your lightbox functionality work smoothly. Add the following JavaScript code to your existing script or create a new JavaScript file:

/*! Image Lightbox Script
 * Copyright: Deo Kumar - Fineshop Design
 * License: MIT
 */
(function (options) {
  function getType (e) {
      return Object.prototype.toString.call(e).replace(/(?:^\[object\s(.*?)\]$)/,"$1").toLowerCase();
  }
  const images = Array.prototype.filter.call(
      getType(options.selectors) === "string" ?
          document.querySelectorAll(options.selectors) :
          (getType(options.selectors) === "array" ?
            document.querySelectorAll(options.selectors.join(",")) :
            []),
      function (image) {
          return image.tagName === "IMG" && (getType(options.ignoreClass) === "string" && options.ignoreClass ? !image.classList.contains(options.ignoreClass) : true);
      }
  );
  if (images.length === 0) {
      return;
  }
  const lightBox = document.createElement("div");
  lightBox.className = options.classes.lightboxWrapper;
  lightBox.addEventListener("click", function (event) {
      lightBox.classList.remove("active");
  });
  lightBox.addEventListener("transitionend", function (event) {
      if (event.propertyName === "opacity" && getComputedStyle(lightBox).getPropertyValue("opacity") === "0" && !lightBox.classList.contains("active")) {
          lightBox.parentNode.removeChild(lightBox);
      }
  });
  images.forEach(function (image) {
      const imageContainer = document.createElement("div");
      imageContainer.className = options.classes.imageWrapper;
      image.parentNode.insertBefore(imageContainer, image);
      imageContainer.appendChild(image);
      imageContainer.addEventListener("click", function (event) {
          event.preventDefault();
          lightBox.innerHTML = image.outerHTML;
          document.body.appendChild(lightBox);
          setTimeout(function () {
              lightBox.classList.add("active");
          }, 40);
      });
  });
}).call(this, {
  selectors: "#postBody img",
  ignoreClass: "noLb",
  classes: {
    imageWrapper: "lbImg",
    lightboxWrapper: "zmImg"
  }
});

This code will listen for clicks on your gallery images and display the selected image in the lightbox. It will also allow users to close the lightbox by clicking the close button.

Conclusion

By creating a custom lightbox image with vanilla JavaScript, you gain full control over its functionality and appearance. This allows you to seamlessly integrate it into your website's design, providing a delightful image viewing experience for your users. Remember to tailor the styles and functionality to meet your project's unique requirements, and enjoy enhancing your website's user experience with this versatile feature. Happy coding!

About the author

Deo Kumar
~ Hello World!

Post a Comment

To avoid SPAM, all comments will be moderated before being displayed.