Image Lightbox – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Wed, 17 May 2023 07:09:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Responsive Masonry Image Gallery with Lightbox in HTML CSS & JavaScript https://www.codingnepalweb.com/masonry-image-gallery-with-lightbox-html-css/ https://www.codingnepalweb.com/masonry-image-gallery-with-lightbox-html-css/#respond Sun, 23 Apr 2023 09:15:40 +0000 https://www.codingnepalweb.com/?p=4098 Responsive Masonry Image Gallery with Lightbox in HTML CSS & JavaScript

Masonry image galleries are an excellent choice for displaying images on websites because they offer a unique and visually appealing layout. However, adding a lightbox effect to the images makes them even better, as it allows users to view the images in more detail.

In this blog post, I will guide you through creating a Responsive Masonry Image Gallery with a Lightbox Effect. The process is straightforward, and even beginners can follow along with ease. We will use HTML, CSS, and JavaScript to create the gallery and style it, ensuring that it is responsive and works well on various devices.

The gallery’s standout feature is its responsive design, meaning it will look great on any device, from desktops to mobile phones. As you create this image gallery, you will gain valuable knowledge about web development, such as building layouts using HTML, styling elements with CSS and making them responsive, and other essential JavaScript concepts.

Steps For Creating Image Gallery with Lightbox in HTML & CSS

To create a responsive masonry image gallery with lightbox effect using HTML, CSS, and vanilla JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js
  5. Download the images folder from Google Drive and put this folder inside the project folder. This static image is only used as a search section background.

Masonry Image Gallery with Lightbox in HTML CSS and JavaScript

To start, add the following HTML codes to your index.html file to create a basic layout for the masonry image gallery with image lightbox.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Masonry Image Gallery with Lightbox | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Masonry Image Gallery with Lightbox</h1>
    <div class="lightbox">
      <div class="wrapper">
        <header>
          <div class="details">
            <i class="uil uil-camera"></i>
            <span>Image Preview</span>
          </div>
          <div class="buttons"><i class="close-icon uil uil-times"></i></div>
        </header>
        <div class="preview-img">
          <div class="img"><img src="" alt="preview-img"></div>
        </div>
      </div>
    </div>
    <section class="gallery">
      <ul class="images">
        <li class="img"><img src="images/img-1.jpg" alt="img"></li>
        <li class="img"><img src="images/img-2.jpg" alt="img"></li>
        <li class="img"><img src="images/img-3.jpg" alt="img"></li>
        <li class="img"><img src="images/img-4.jpg" alt="img"></li>
        <li class="img"><img src="images/img-5.jpg" alt="img"></li>
        <li class="img"><img src="images/img-6.jpg" alt="img"></li>
        <li class="img"><img src="images/img-7.jpg" alt="img"></li>
        <li class="img"><img src="images/img-8.jpg" alt="img"></li>
        <li class="img"><img src="images/img-9.jpg" alt="img"></li>
        <li class="img"><img src="images/img-10.jpg" alt="img"></li>
        <li class="img"><img src="images/img-11.jpg" alt="img"></li>
      </ul>
    </section>

  </body>
</html>

Next, add the following CSS codes to your style.css file to give a masonry layout for the image gallery and make an image lightbox. Keep in mind that the lightbox is now hidden because I’ve added some CSS properties to hide it. We’ll show it on image click using JavaScript.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
h1 {
  text-align: center;
  margin-top: 50px;
}
/* Masonry image gallery styling */
.gallery {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.gallery .images {
  gap: 15px;
  max-width: 85%;
  margin: 40px 0;
  columns: 5 310px;
  list-style: none;
}
.gallery .images .img {
  display: flex;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  margin-bottom: 14px;
  border-radius: 4px;
}
.gallery .images img {
  width: 100%;
  transition: transform 0.2s ease;
}

.gallery .images .img:hover img {
  transform: scale(1.1);
}

/* Image lightbox styling */
.lightbox {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
  position: fixed;
  visibility: hidden;
  background: rgba(0,0,0,0.65);
}
.lightbox.show {
  visibility: visible;
}
.lightbox .wrapper {
  position: fixed;
  left: 50%;
  top: 50%;
  width: 100%;
  padding: 20px;
  max-width: 850px;
  background: #fff;
  border-radius: 6px;
  opacity: 0;
  pointer-events: none;
  transform: translate(-50%, -50%) scale(0.9);
  transition: transform 0.1s ease;
}
.lightbox.show .wrapper {
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
}
.wrapper :where(header, .details) {
  display: flex;
  align-items: center;
}
.wrapper header {
  justify-content: space-between;
}
header .details i {
  font-size: 1.7rem;
}
header .details span {
  font-size: 1.2rem;
  margin-left: 10px;
}
header .buttons i {
  height: 40px;
  width: 40px;
  cursor: pointer;
  display: inline-block;
  color: #fff;
  margin-left: 10px;
  background: #6C757D;
  font-size: 1.25rem;
  line-height: 40px;
  text-align: center;
  border-radius: 4px;
  transition: 0.2s ease;
}
header .buttons i:hover {
  background: #5f666d;
}
.wrapper .preview-img {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
.preview-img .img {
  max-height: 65vh;
}
.preview-img img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* Responsive media query code */
@media screen and (max-width: 688px) {
  .lightbox .wrapper {
    padding: 12px;
    max-width: calc(100% - 26px);
  }
  .wrapper .preview-img {
    margin-top: 15px;
  }
  .gallery .images {
    max-width: 100%;
    padding: 0 13px;
    margin-top: 20px;
  }
}

Finally, add the following JavaScript code to your script.js file to show a lightbox when the user clicks on the specific image and then hide the lightbox when they click on the close icon.

const allImages = document.querySelectorAll(".images .img");
const lightbox = document.querySelector(".lightbox");
const closeImgBtn = lightbox.querySelector(".close-icon");

allImages.forEach(img => {
    // Calling showLightBox function with passing clicked img src as argument
    img.addEventListener("click", () => showLightbox(img.querySelector("img").src));
});

const showLightbox = (img) => {
    // Showing lightbox and updating img source
    lightbox.querySelector("img").src = img;
    lightbox.classList.add("show");
    document.body.style.overflow = "hidden";
}

closeImgBtn.addEventListener("click", () => {
    // Hiding lightbox on close icon click
    lightbox.classList.remove("show");
    document.body.style.overflow = "auto";
});

In short, we started by creating a simple unordered list structure of images, styling it using CSS to create a masonry layout, and adding a div with the class “lightbox” to contain the image preview and close button. Finally, we added JavaScript code to show and hide the lightbox as needed.

Conclusion and Final Words

By following the steps in this blog post, I hope you were able to create a masonry image gallery with a lightbox effect using HTML, CSS, and JavaScript. The code and logic behind creating this image gallery were quite simple and easy to follow.

If you’re eager to enhance your web development skills further, why not explore our blog on Creating a Functional Image Gallery in HTML, CSS, and JavaScript? This informative post guides you through the process of creating an image gallery that lets users search for, view, and download images.

If you encounter any problems or your code is not working as expected, you can download the source code files for this masonry image gallery for free. Click on the download button to get the zip file containing the project folder with source code files and images.

 

]]>
https://www.codingnepalweb.com/masonry-image-gallery-with-lightbox-html-css/feed/ 0
Create Functional Image Gallery in HTML CSS & JavaScript https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/ https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/#comments Tue, 04 Apr 2023 17:42:09 +0000 https://www.codingnepalweb.com/?p=4077 Create Functional Image Gallery in HTML CSS & JavaScript

If you’re a web designer or developer, you must have searched for copyright-free images for your projects on various websites. Pexels is one of the most popular sites for such images. But as a web developer, have you ever wanted to create a functional image gallery similar to Pexels?

In this blog post, I’ll show the steps for creating a fully-functional image gallery using HTML, CSS, and JavaScript. Not only will you learn the basics of DOM manipulation, event handling, and CSS styling, but you’ll also gain valuable experience working with APIs.

With this Pexels clone coding project, you can effortlessly search, view, and download any image you desire, all within seconds. The images are displayed in a stylish masonry layout which looks great on any device, from desktops to mobile phones.

If you’re excited to see a live demo of this image gallery, click here to check it out. For a full video tutorial on creating a functional image gallery using HTML, CSS, and JavaScript, you can watch the given YouTube video.

Video Tutorial of Functional Image Gallery in JavaScript

If you prefer visual learning, then the above video tutorial is a great resource for you. I highly recommend watching it because I go through each line of code in detail and provide comments to help you understand what’s happening at each step.

But if you prefer reading blog posts or want a quick summary of the steps involved in creating an image gallery, you can continue reading this post. By the end of this post, you will have a clear understanding of how to create your very own Pexels clone image gallery with HTML, CSS, and JavaScript.

Steps For Creating Image Gallery in JavaScript

To create a functional image gallery using HTML, CSS, and vanilla JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want, and inside this folder, create the mentioned files.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js
  5. Download the images folder from Google Drive and put this folder inside the project folder. This static image is only used as a search section background.

To start, add the following HTML codes to your index.html file to create a basic layout for an image gallery. Note that the “ul” container is currently empty, but it will be filled with “li” elements (representing image cards) later using JavaScript code.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Image Gallery with JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="lightbox">
      <div class="wrapper">
        <header>
          <div class="photographer">
            <i class="uil uil-camera"></i>
            <span></span>
          </div>
          <div class="buttons">
            <i class="uil uil-import"></i>
            <i class="close-icon uil uil-times"></i>
          </div>
        </header>
        <div class="preview-img">
          <div class="img"><img src="" alt="preview-img"></div>
        </div>
      </div>
    </div>
    <section class="search">
      <img src="./images/search-img.jpg" alt="search-img">
      <div class="content">
        <h1>Image Gallery with JavaScript</h1>
        <p>Search and download any images within a second</p>
        <div class="search-box">
          <i class="uil uil-search"></i>
          <input type="text" placeholder="Search images">
        </div>
      </div>
    </section>
    <section class="gallery">
      <ul class="images"></ul>
      <button class="load-more">Load More</button>
    </section>

  </body>
</html>

Next, add the following CSS codes to your style.css file to give a basic look and feel to the image gallery. If you wish, you can customize it to your liking by changing the color, font, size, and other CSS properties in the file.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
.search {
  height: 40vh;
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
}
.search::before, .search img, .lightbox {
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  position: absolute;
}
.search::before {
  content: "";
  z-index: 1;
  background: rgba(0,0,0,0.25);
}
.search img {
  object-fit: cover;
}
.search .content {
  z-index: 2;
  color: #fff;
  padding: 0 13px;
  text-align: center;
  position: relative;
}
.search h1 {
  font-size: 2.65rem;
  font-weight: 600;
}
.search p {
  margin-top: 8px;
  font-size: 1.5rem;
}
.search .search-box {
  height: 55px;
  margin: 45px 0;
  position: relative;
}
.search-box i {
  position: absolute;
  left: 20px;
  top: 50%;
  cursor: default;
  color: #8D8D8D;
  font-size: 1.4rem;
  transform: translateY(-50%);
}
.search-box input {
  width: 100%;
  height: 100%;
  outline: none;
  border: none;
  font-size: 1.1rem;
  padding-left: 55px;
  background: #fff;
  border-radius: 5px;
}
.search-box input::placeholder {
  color: #929292;
}
.search-box input:focus::placeholder {
  color: #bfbfbf;
}
.gallery {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.gallery .images {
  gap: 15px;
  max-width: 95%;
  margin-top: 40px;
  columns: 5 340px;
  list-style: none;
}
.gallery .images .card {
  display: flex;
  cursor: pointer;
  overflow: hidden;
  position: relative;
  margin-bottom: 14px;
  border-radius: 4px;
}
.gallery .images img {
  width: 100%;
  z-index: 2;
  position: relative;
}
.images .details {
  position: absolute;
  z-index: 4;
  width: 100%;
  bottom: -100px;
  display: flex;
  align-items: center;
  padding: 15px 20px;
  justify-content: space-between;
  transition: bottom 0.1s ease;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
}
.images li:hover .details {
  bottom: 0;
}
.photographer {
  color: #fff;
  display: flex;
  align-items: center;
}
.photographer i {
  font-size: 1.4rem;
  margin-right: 10px;
}
.photographer span {
  font-size: 1.05rem;
}
button, i {
  outline: none;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  transition: 0.2s ease;
}
.details button {
  background: #fff;
  font-size: 1.1rem;
  padding: 3px 8px;
}
.details .download-btn:hover {
  background: #f2f2f2;
}
.gallery .load-more {
  color: #fff;
  background: #8A6CFF;
  margin: 50px 0;
  font-size: 1.2rem;
  padding: 12px 27px;
}
.gallery .load-more.disabled {
  opacity: 0.6;
  pointer-events: none;
}
.gallery .load-more:hover {
  background: #704dff;
}

.lightbox {
  z-index: 5;
  position: fixed;
  visibility: hidden;
  background: rgba(0,0,0,0.65);
}
.lightbox.show {
  visibility: visible;
}
.lightbox .wrapper {
  position: fixed;
  left: 50%;
  top: 50%;
  width: 100%;
  padding: 20px;
  max-width: 850px;
  background: #fff;
  border-radius: 6px;
  opacity: 0;
  pointer-events: none;
  transform: translate(-50%, -50%) scale(0.9);
  transition: transform 0.1s ease;
}
.lightbox.show .wrapper {
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
}
.wrapper header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
header .photographer {
  color: #333;
}
header .photographer i {
  font-size: 1.7rem;
  cursor: auto;
}
header .photographer span {
  font-size: 1.2rem;
}
header .buttons i {
  height: 40px;
  width: 40px;
  display: inline-block;
  color: #fff;
  font-size: 1.2rem;
  line-height: 40px;
  text-align: center;
  background: #8A6CFF;
  border-radius: 4px;
  transition: 0.2s ease;
}
header .buttons i:first-child:hover {
  background: #704dff;
}
header .buttons i:last-child {
  margin-left: 10px;
  font-size: 1.25rem;
  background: #6C757D;
}
header .buttons i:last-child:hover {
  background: #5f666d;
}
.wrapper .preview-img {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
.preview-img .img {
  max-height: 65vh;
}
.preview-img img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

@media screen and (max-width: 688px) {
  .lightbox .wrapper {
    padding: 12px;
    max-width: calc(100% - 26px);
  }
  .wrapper .preview-img {
    margin-top: 15px;
  }
  header .buttons i:last-child {
    margin-left: 7px;
  }
  header .photographer span, .search p {
    font-size: 1.1rem;
  }
  .search h1 {
    font-size: 1.8rem;
  }
  .search .search-box {
    height: 50px;
    margin: 30px 0;
  }
  .gallery .images {
    max-width: 100%;
    padding: 0 13px;
    margin-top: 20px;
  }
  .images .details {
    bottom: 0px;
  }
  .gallery .load-more {
    padding: 10px 25px;
    font-size: 1.05rem;
  }
}

Finally, add the following JavaScript code to your script.js file to add functionality for searching, viewing, and downloading images from this gallery. This code will handle user actions and communicate with the Pexels API to retrieve and display images in the gallery.

const imageWrapper = document.querySelector(".images");
const searchInput = document.querySelector(".search input");
const loadMoreBtn = document.querySelector(".gallery .load-more");
const lightbox = document.querySelector(".lightbox");
const downloadImgBtn = lightbox.querySelector(".uil-import");
const closeImgBtn = lightbox.querySelector(".close-icon");

// API key, paginations, searchTerm variables
const apiKey = "PASTE-YOUR-API-KEY";
const perPage = 15;
let currentPage = 1;
let searchTerm = null;

const downloadImg = (imgUrl) => {
    // Converting received img to blob, creating its download link, & downloading it
    fetch(imgUrl).then(res => res.blob()).then(blob => {
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = new Date().getTime();
        a.click();
    }).catch(() => alert("Failed to download image!"));
}

const showLightbox = (name, img) => {
    // Showing lightbox and setting img source, name and button attribute
    lightbox.querySelector("img").src = img;
    lightbox.querySelector("span").innerText = name;
    downloadImgBtn.setAttribute("data-img", img);
    lightbox.classList.add("show");
    document.body.style.overflow = "hidden";
}

const hideLightbox = () => {
    // Hiding lightbox on close icon click
    lightbox.classList.remove("show");
    document.body.style.overflow = "auto";
}

const generateHTML = (images) => {
    // Making li of all fetched images and adding them to the existing image wrapper
    imageWrapper.innerHTML += images.map(img =>
        `<li class="card">
            <img onclick="showLightbox('${img.photographer}', '${img.src.large2x}')" src="${img.src.large2x}" alt="img">
            <div class="details">
                <div class="photographer">
                    <i class="uil uil-camera"></i>
                    <span>${img.photographer}</span>
                </div>
                <button onclick="downloadImg('${img.src.large2x}');">
                    <i class="uil uil-import"></i>
                </button>
            </div>
        </li>`
    ).join("");
}

const getImages = (apiURL) => {
    // Fetching images by API call with authorization header
    searchInput.blur();
    loadMoreBtn.innerText = "Loading...";
    loadMoreBtn.classList.add("disabled");
    fetch(apiURL, {
        headers: { Authorization: apiKey }
    }).then(res => res.json()).then(data => {
        generateHTML(data.photos);
        loadMoreBtn.innerText = "Load More";
        loadMoreBtn.classList.remove("disabled");
    }).catch(() => alert("Failed to load images!"));
}

const loadMoreImages = () => {
    currentPage++; // Increment currentPage by 1
    // If searchTerm has some value then call API with search term else call default API
    let apiUrl = `https://api.pexels.com/v1/curated?page=${currentPage}&per_page=${perPage}`;
    apiUrl = searchTerm ? `https://api.pexels.com/v1/search?query=${searchTerm}&page=${currentPage}&per_page=${perPage}` : apiUrl;
    getImages(apiUrl);
}

const loadSearchImages = (e) => {
    // If the search input is empty, set the search term to null and return from here
    if (e.target.value === "") return searchTerm = null;
    // If pressed key is Enter, update the current page, search term & call the getImages
    if (e.key === "Enter") {
        currentPage = 1;
        searchTerm = e.target.value;
        imageWrapper.innerHTML = "";
        getImages(`https://api.pexels.com/v1/search?query=${searchTerm}&page=1&per_page=${perPage}`);
    }
}

getImages(`https://api.pexels.com/v1/curated?page=${currentPage}&per_page=${perPage}`);
loadMoreBtn.addEventListener("click", loadMoreImages);
searchInput.addEventListener("keyup", loadSearchImages);
closeImgBtn.addEventListener("click", hideLightbox);
downloadImgBtn.addEventListener("click", (e) => downloadImg(e.target.dataset.img));

In the code, you will notice a variable called apiKey. You need to get your own Pexels API key and insert it into this variable. You can get a free API key by visiting the official Pexels API documentation. Additionally, you will find a variable named perPage, which has a default value of 15. This means that every time the API is called, 15 new images will be fetched.

Conclusion and Final Words

Creating a functional image gallery using HTML, CSS, and JavaScript is an excellent project for beginners to learn about web development concepts such as DOM manipulation, event handling, CSS styling, and API usage in real-world projects.

With the knowledge and skills you’ve gained from this project, now it’s up to you to experiment with the code and take this image gallery to the next level. For more API-related coding projects, check out the blog on Top JavaScript APIs Projects for Beginners.

If you encounter any problems or your code is not working as expected, you can download the source code files for this image gallery for free. Click on the download button to get the zip file containing the project folder with source code files. Remember to paste your API key into the code.

 

]]>
https://www.codingnepalweb.com/functional-image-gallery-html-css-javascript/feed/ 1
Responsive Image Lightbox using HTML CSS & JavaScript https://www.codingnepalweb.com/responsive-image-lightbox-javascript/ https://www.codingnepalweb.com/responsive-image-lightbox-javascript/#comments Mon, 04 Jan 2021 09:52:00 +0000 Responsive Image Lightbox using HTML CSS & JavaScript
Hey friends, today in this blog you’ll learn how to create Responsive Image Lightbox using HTML CSS & JavaScript. Earlier I have shared a blog on how to create a Responsive Filterable Image Gallery in JavaScript and now it’s time to create Image Lightbox.

You may have seen image lightbox on many websites. Lightbox showcases images and videos by filling the screen and dimming out the rest of the web page. In the image lightbox, there are slide controls so you can easily change the image to next or previous. There are many JavaScript libraries for lightbox but today in this blog I’ll show you how to create lightbox without using the JavaScript library or jQuery plugin.

In this program [Responsive Image Lightbox], there are six images on the webpage and when you click on the particular image then the lightbox appears with the selected image. In the lightbox, there is a total image and current image number on the top left side and a cross icon on the top right side. There are also previous and next icons to change the image. When you click on the cross icon then the lightbox will disappear and after again clicking on the particular image, the lightbox appears.

This image gallery and lightbox are fully responsive for all devices. On the pc, there are 3 three images in a single row but on the mobile devices, there is only one image in the single row. If you’re feeling difficulty understanding what I’m saying then you can watch a full video tutorial of this responsive image lightbox.

Video Tutorial of Responsive Image Lightbox 

 
In the video, you have seen the preview or demo of the responsive image lightbox and how I created this. As you know, I didn’t use any JavaScript library to create this image lightbox. If you’re a beginner then you may have difficulties to understanding the JavaScript codes of this program but don’t worry I’ve tried to explain each JavaScript line with writing comments so once you download the code files you’ll easily understand the codes.

You might like this:

Responsive Image Lightbox [Source Codes]

To create this program [Responsive Image Lightbox]. First, you need to create three files, HTML File, CSS File, and JavaScript File. After creating these files just paste the following codes into your files. You can also download the source code files of this image lightbox from the given download button.

First, create an HTML file with the name of index.html and paste the given codes in your HTML file. Remember, you’ve to create a file with .html extension and the images that are used on this lightbox won’t appear. You’ve to download files from the given download button to use images also.

<!DOCTYPE html>
<!-- Created By CodingNepal - www.codingnepalweb.com -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--- Don't forget to add this meta tag otherwise your design won't responsive ---->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Image Lightbox | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <div class="wrapper">
    <div class="gallery">
      <div class="image"><span><img src="images/img-1.jpg" alt=""></span></div>
      <div class="image"><span><img src="images/img-2.jpg" alt=""></span></div>
      <div class="image"><span><img src="images/img-3.jpg" alt=""></span></div>
      <div class="image"><span><img src="images/img-4.jpg" alt=""></span></div>
      <div class="image"><span><img src="images/img-5.jpg" alt=""></span></div>
      <div class="image"><span><img src="images/img-6.jpg" alt=""></span></div>
    </div>
  </div>
  <div class="preview-box">
    <div class="details">
      <span class="title">Image <p class="current-img"></p> of <p class="total-img"></p></span>
      <span class="icon fas fa-times"></span>
    </div>
    <div class="image-box">
      <div class="slide prev"><i class="fas fa-angle-left"></i></div>
      <div class="slide next"><i class="fas fa-angle-right"></i></div>
      <img src="" alt="">
    </div>
  </div>
  <div class="shadow"></div>

  <script src="script.js"></script>

</body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
::selection{
  color: #fff;
  background: #007bff;
}
body{
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}
.wrapper{
  max-width: 1100px;
}
.gallery{
  display: flex;
  flex-wrap: wrap;
}
.gallery .image{
  padding: 7px;
  width: calc(100% / 3);
}
.gallery .image span{
  display: flex;
  width: 100%;
  overflow: hidden;
}
.gallery .image img{
  width: 100%;
  vertical-align: middle;
  transition: all 0.3s ease;
}
.gallery .image:hover img{
  transform: scale(1.1);
}

.preview-box{
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.9);
  background: #fff;
  max-width: 700px;
  width: 100%;
  z-index: 5;
  opacity: 0;
  pointer-events: none;
  border-radius: 3px;
  padding: 0 5px 5px 5px;
  box-shadow: 0px 0px 15px rgba(0,0,0,0.2);
}
.preview-box.show{
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
  transition: all 0.3s ease;
}
.preview-box .details{
  display: flex;
  align-items: center;
  padding: 12px 15px 12px 10px;
  justify-content: space-between;
}
.preview-box .details .title{
  display: flex;
  font-size: 18px;
  font-weight: 400;
}
.details .title p{
  margin: 0 5px;
}
.details .title p.current-img{
  font-weight: 500;
}
.details .icon{
  color: #007bff;
  font-size: 20px;
  cursor: pointer;
}
.preview-box .image-box{
  display: flex;
  width: 100%;
  position: relative;
}
.image-box .slide{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  font-size: 30px;
  cursor: pointer;
  height: 50px;
  width: 60px;
  line-height: 50px;
  text-align: center;
  border-radius: 3px;
}
.slide.prev{
  left: 0px;
}
.slide.next{
  right: 0px;
}
.image-box img{
  width: 100%;
  border-radius: 0 0 3px 3px;
}
.shadow{
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  z-index: 2;
  display: none;
  background: rgba(0,0,0,0.45);
}

@media(max-width: 1000px){
  .gallery .image{
    width: calc(100% / 2);
  }
}
@media(max-width: 600px){
  .gallery .image{
    width: 100%;
    padding: 4px;
  }
}

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.

//getting all required elements
const gallery  = document.querySelectorAll(".image"),
previewBox = document.querySelector(".preview-box"),
previewImg = previewBox.querySelector("img"),
closeIcon = previewBox.querySelector(".icon"),
currentImg = previewBox.querySelector(".current-img"),
totalImg = previewBox.querySelector(".total-img"),
shadow = document.querySelector(".shadow");

window.onload = ()=>{
    for (let i = 0; i < gallery.length; i++) {
        totalImg.textContent = gallery.length; //passing total img length to totalImg variable
        let newIndex = i; //passing i value to newIndex variable
        let clickedImgIndex; //creating new variable
        
        gallery[i].onclick = () =>{
            clickedImgIndex = i; //passing cliked image index to created variable (clickedImgIndex)
            function preview(){
                currentImg.textContent = newIndex + 1; //passing current img index to currentImg varible with adding +1
                let imageURL = gallery[newIndex].querySelector("img").src; //getting user clicked img url
                previewImg.src = imageURL; //passing user clicked img url in previewImg src
            }
            preview(); //calling above function
    
            const prevBtn = document.querySelector(".prev");
            const nextBtn = document.querySelector(".next");
            if(newIndex == 0){ //if index value is equal to 0 then hide prevBtn
                prevBtn.style.display = "none"; 
            }
            if(newIndex >= gallery.length - 1){ //if index value is greater and equal to gallery length by -1 then hide nextBtn
                nextBtn.style.display = "none"; 
            }
            prevBtn.onclick = ()=>{ 
                newIndex--; //decrement index
                if(newIndex == 0){
                    preview(); 
                    prevBtn.style.display = "none"; 
                }else{
                    preview();
                    nextBtn.style.display = "block";
                } 
            }
            nextBtn.onclick = ()=>{ 
                newIndex++; //increment index
                if(newIndex >= gallery.length - 1){
                    preview(); 
                    nextBtn.style.display = "none";
                }else{
                    preview(); 
                    prevBtn.style.display = "block";
                }
            }
            document.querySelector("body").style.overflow = "hidden";
            previewBox.classList.add("show"); 
            shadow.style.display = "block"; 
            closeIcon.onclick = ()=>{
                newIndex = clickedImgIndex; //assigning user first clicked img index to newIndex
                prevBtn.style.display = "block"; 
                nextBtn.style.display = "block";
                previewBox.classList.remove("show");
                shadow.style.display = "none";
                document.querySelector("body").style.overflow = "scroll";
            }
        }
        
    } 
}

That’s all, now you’ve successfully created a Responsive Image Lightbox using HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any error/problem then please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

 

]]>
https://www.codingnepalweb.com/responsive-image-lightbox-javascript/feed/ 11