Basic Responsive Gallery In Vanilla JavaScript

Category: Gallery , Javascript | January 30, 2018
Author:joe-ashworth
Views Total:3,310 views
Official Page:Go to website
Last Update:January 30, 2018
License:MIT

Preview:

Basic Responsive Gallery In Vanilla JavaScript

Description:

A lightweight script to create a responsive gallery where you can navigate between images by clicking the thumbnails.

How to use it:

Insert thumbnails and the first image to the gallery as these:

<div class="container">
  <div class="panel-main">
    <img src="https://picsum.photos/1920/1200?image=797" id="selected">
  </div>
  <div class="thumbs">
    <img src="https://picsum.photos/1920/1200?image=797">
    <img src="https://picsum.photos/1920/1200?image=777">
    <img src="https://picsum.photos/1920/1200?image=755">
    <img src="https://picsum.photos/1920/1200?image=838">
    <img src="https://picsum.photos/1920/1200?image=839">
  </div>
</div>

Style the gallery and make it responsive using CSS flexbox:

.container {
  max-width: 800px;
  margin: auto;
  border: white solid 5px;
  background-color: white;
}
.panel-main img, .thumbs img {
  width: 100%;
  height: auto;
}
.thumbs {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 5px;
}

Apply a fading animation to the gallery when you switch between images.

@keyframes 
fadeIn {  to {
 opacity: 1;
}
}
.fade-in {
  opacity: 0;
  animation: fadeIn 0.5s ease-in 1 forwards;
}

The JavaScript to activate the gallery.

const current = document.querySelector("#selected");
const thumbs = document.querySelectorAll(".thumbs img");
const opacity = 0.5;
// Set opacity of first image
thumbs[0].style.opacity = opacity;
thumbs.forEach(img => img.addEventListener("click", imgActivate));
function imgActivate(e) {
  // Reset opacity on all thumbs
  thumbs.forEach(img => (img.style.opacity = 1));
  // Change current image to source of clicked image
  current.src = e.target.src;
  // Add fadeIn class
  current.classList.add("fade-in");
  // Remove fadeIn class after animation time elapsed
  setTimeout(() => current.classList.remove("fade-in"), 500);
  // Change opacity to variable value
  e.target.style.opacity = opacity;
}

You Might Be Interested In:


One thought on “Basic Responsive Gallery In Vanilla JavaScript

  1. Satoshi A Seth

    How would I go about putting two of these on the same page?

    Reply

Leave a Reply