Basic Responsive Gallery In Vanilla JavaScript

Category: Gallery , Javascript | January 30, 2018
Views Total:3,430 views
Official Page:Go to website
Last Update:January 30, 2018


Basic Responsive Gallery In Vanilla JavaScript


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="" id="selected">
  <div class="thumbs">
    <img src="">
    <img src="">
    <img src="">
    <img src="">
    <img src="">

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.

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 => ( = 1));
  // Change current image to source of clicked image
  current.src =;
  // Add fadeIn class
  // Remove fadeIn class after animation time elapsed
  setTimeout(() => current.classList.remove("fade-in"), 500);
  // Change opacity to variable value = 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?


Leave a Reply