Lightweight JavaScript Lightbox with Caption

Lightweight JavaScript Lightbox
Project: Lightbox gallery
Author: Stan
Edit Online: View on CodePen
License: MIT

This JavaScript code project helps you to create a lightweight image lightbox with a caption. It creates a simple lightbox gallery for a group of images. When an image in the gallery is clicked, a lightbox is displayed containing the full-size version of the image and a caption.

It prevents the default behavior of navigating to the image’s link and retrieves the data-image-hd attribute value as the image source and the alt attribute value as the image caption.

How to Create Lightweight JavaScript Lightbox

First of all, load the Modernizr JS, Bootstrap CSS, and Font Awesome CSS by adding the following CDN links into the head tag of your HTML document.

<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>

Create the HTML structure as follows:

<div class="container">
		<h2 class="text-center">Lightbox Gallery</h2>
		<div class="lightbox-gallery">
				<div><img src="https://picsum.photos/id/343/300/300" data-image-hd="https://picsum.photos/id/343/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit, quae, quam. Ut dolorum quia, unde dicta at harum porro officia obcaecati ipsam deserunt fugit dolore delectus quam, maxime nisi quo."></div>
				<div><img src="https://picsum.photos/id/112/300/300" data-image-hd="https://picsum.photos/id/112/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Maxime accusamus officiis dignissimos doloribus consectetur harum eos sapiente optio aut minima."></div>
				<div><img src="https://picsum.photos/id/155/300/300" data-image-hd="https://picsum.photos/id/155/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates veritatis similique, amet, maiores soluta recusandae cupiditate, sed perspiciatis fugit minima, sunt dolores cum earum deserunt illo ipsum!"></div>
				<div><img src="https://picsum.photos/id/11/300/300" data-image-hd="https://picsum.photos/id/11/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque laudantium dignissimos tenetur eos unde quidem repellat officiis nemo laboriosam necessitatibus deleniti commodi quis aliquid est atque tempora aut, nihil!"></div>
				<div><img src="https://picsum.photos/id/434/300/300" data-image-hd="https://picsum.photos/id/434/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto minus consequatur soluta quaerat itaque, laboriosam quis a facilis, cumque, deleniti quas aperiam voluptate dolore. Enim nostrum sit eaque, porro eligendi illo placeat?"></div>
				<div><img src="https://picsum.photos/id/101/300/300" data-image-hd="https://picsum.photos/id/101/600/600" alt="Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi suscipit quam, id aliquam totam aperiam quas rem debitis voluptatem pariatur, illo accusamus facilis eius ipsa! Reprehenderit libero, quas iste repudiandae distinctio, quos dignissimos."></div>
		</div>
	</div>

<div class="text-center github-link">
  <a class="github-link" href="https://github.com/humbl3man/lightboxify" target="_blank"><i class="fa fa-github"></i> Github Source Code</a>
</div>

Style the lightbox using the following CSS styles:

body {
  background-color: #3bb2b8;
  background: linear-gradient(
    25deg,
    rgba(66, 230, 149, 1),
    rgba(66, 32, 149, 1)
  );
  background-repeat: no-repeat;
  height: 100vh;
  font-family: "Open Sans", sans-serif;
}
.container {
  max-width: 800px;
  margin: 5% auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-sizing: border-box;
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.4);
}

.text-center {
  text-align: center;
  margin-bottom: 1em;
}

.lightbox-gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.lightbox-gallery div > img {
  max-width: 100%;
  display: block;
}

.lightbox-gallery div {
  margin: 10px;
  flex-basis: 180px;
}

@media only screen and (max-width: 480px) {
  .lightbox-gallery {
    flex-direction: column;
    align-items: center;
  }

  .lightbox > div {
    margin-bottom: 10px;
  }
}

/*Lighbox CSS*/

.lightbox {
  display: none;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 20;
  padding-top: 30px;
  box-sizing: border-box;
}

.lightbox img {
  display: block;
  margin: auto;
}

.lightbox .caption {
  margin: 15px auto;
  width: 50%;
  text-align: center;
  font-size: 1em;
  line-height: 1.5;
  font-weight: 700;
  color: #eee;
}

.github-link {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.7);
}

.github-link:hover,
.github-link:active,
.github-link:visited {
  color: #fff;
  text-decoration: none;
}

Now, load the jQuery by adding the following CDN link before closing the body tag:

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

Finally, add the following JavaScript function to initialize the lightbox:

// Create a lightbox
(function() {
  var $lightbox = $("<div class='lightbox'></div>");
  var $img = $("<img>");
  var $caption = $("<p class='caption'></p>");

  // Add image and caption to lightbox

  $lightbox
    .append($img)
    .append($caption);

  // Add lighbox to document

  $('body').append($lightbox);

  $('.lightbox-gallery img').click(function(e) {
    e.preventDefault();

    // Get image link and description
    var src = $(this).attr("data-image-hd");
    var cap = $(this).attr("alt");

    // Add data to lighbox

    $img.attr('src', src);
    $caption.text(cap);

    // Show lightbox

    $lightbox.fadeIn('fast');

    $lightbox.click(function() {
      $lightbox.fadeOut('fast');
    });
  });

}());

Code Explanation

First, an anonymous function is created and immediately executed. This is done to keep the variables within the function from interfering with any other code on the page.

Within the function, three variables are created: $lightbox, $img, and $caption. $lightbox is a new <div> element with a class of lightbox, while $img is a new <img> element and $caption is a new <p> element with a class of caption.

The $img and $caption elements are then added to the $lightbox element using the append() method.

Next, the $lightbox element is added to the <body> of the document using the append() method.

Finally, an event listener is added to each image in the .lightbox-gallery. When an image is clicked, the lightbox appears with the clicked image and its caption. The preventDefault() method is called on the event to prevent the default action (i.e., following the link to the image) from occurring. The src and alt attributes of the clicked image are retrieved using the attr() method, and are used to update the $img and $caption elements, respectively. The lightbox is then shown using the fadeIn() method. Another event listener is added to the lightbox to allow the user to close it by clicking anywhere outside of the image and its caption.

That’s all! hopefully, you have successfully created JavaScript Lightbox. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply