Simple Lightbox Image Viewer using jQuery

Enhance the user experience by adding a simple jQuery image viewer aka lightbox without any plugins. Follow this tutorial to do it yourself by only using CSS and JQuery.

Simple Lightbox Image Viewer using jQuery

HTML

Add an img tag with the class “lightbox”.

You can skip the data-target attribute if you want to use the same image in the thumbnail and in the lightbox as well.

<img
  src="https://example.com/your-image-thumb.jpg"
  data-target="https://example.com/your-image-full.jpg"
  class="lightbox"
/>

CSS

Add this css code.

You can adjust the width of the .lightbox class to increase or decrease the width of your thumbnail.

.lightbox {
  cursor: pointer;
  width: 100px;
}
.lightbox-modal {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  width: 100%;
  height: 100%;
  display: flex;
  opacity: 0;
  align-items: center;
  justify-content: center;
  background-color: #000000db;
}
.lightbox-close {
  position: fixed;
  top: 20px;
  right: 20px;
  color: #fff;
  cursor: pointer;
  background-color: #000;
  border: 0;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  font-size: 16px;
  z-index: 2;
}

jQuery

Add an on-click event listener to the .lightbox class inside a document ready function.

Then get the  data-target  or  src  attribute value.

Then inject that into our template, which will be appended to the body.

Then we will animate the opacity of that newly created element to give it a fade-in effect.

Since we are using display:flex; for the .lightbox-modal class, we can’t use jQuery’s built-in .fadeIn() function.

$(document).ready(() => {
  $(".lightbox").on("click", (e) => {
    let el = $(e.target);
    let img = el.attr("data-target") || el.attr("src");

    //Modal template
    let template = `<div class="lightbox-modal">
        <button class="lightbox-close">&#10006;</button>
        <img src="${img}" />
        </div>`;

    //Inject the modal
    $("body").append(template);

    //Fade-In animation
    $(".lightbox-modal").animate(
      {
        opacity: 1,
      },
      "fast",
    );
  });
});

Bind the on-click event to the body, which gets triggered whenever we click anywhere inside the .lightbox-modal class.

Check if we are clicking outside the lightbox image.

If yes, we will animate the opacity to 0, and then we will remove the .lightbox-modal element from the DOM.

$("body").on("click", ".lightbox-modal", (e) => {
  var container = $(".lightbox-modal img");
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    $(".lightbox-modal").animate(
      {
        opacity: 0,
      },
      "fast",
    );
    //Remove the modal
    setTimeout(() => {
      $(".lightbox-modal").remove();
    }, 300);
  }
});
About the Author

Anand Roshan is a full-stack developer with 12+ years of experience in web and app development.